我有一个我想在我的组件之间共享到 Angular2 应用程序中的对象。
这是第一个组件的来源:
/* app.component.ts */
// ...imports
import {ConfigService} from './config.service';
@Component({
selector: 'my-app',
templateUrl: 'app/templates/app.html',
directives: [Grid],
providers: [ConfigService]
})
export class AppComponent {
public size: number;
public square: number;
constructor(_configService: ConfigService) {
this.size = 16;
this.square = Math.sqrt(this.size);
// Here I call the service to put my data
_configService.setOption('size', this.size);
_configService.setOption('square', this.square);
}
}
第二个组成部分:
/* grid.component.ts */
// ...imports
import {ConfigService} from './config.service';
@Component({
selector: 'grid',
templateUrl: 'app/templates/grid.html',
providers: [ConfigService]
})
export class Grid {
public config;
public header = [];
constructor(_configService: ConfigService) {
// issue is here, the _configService.getConfig() get an empty object
// but I had filled it just before
this.config = _configService.getConfig();
}
}
最后是我的小服务 ConfigService:
/* config.service.ts */
import {Injectable} from 'angular2/core';
@Injectable()
export class ConfigService {
private config = {};
setOption(option, value) {
this.config[option] = value;
}
getConfig() {
return this.config;
}
}
我的数据没有共享,在grid.component.ts中,该_configService.getConfig()
行返回一个空对象,但它是在app.component.ts之前填充的。
我阅读了文档和教程,没有任何效果。
我错过了什么?
谢谢
解决了
我的问题是我两次注入了我的 ConfigService。在应用程序的引导程序和我使用它的文件中。
我删除了providers
设置并且它起作用了!