我有一个对象,我想在我的组件之间共享到 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 之前被填充了。
我阅读了文档和教程,但没有任何效果。
我错过了什么?
谢谢
已解决
我的问题是我注入(inject)了我的 ConfigService 两次。在应用程序的 Bootstrap 和我正在使用它的文件中。
我删除了 providers
设置并且它起作用了!
最佳答案
您在两个组件中定义它。所以服务不共享。 AppComponent
组件有一个实例,Grid
组件有另一个实例。
@Component({
selector: 'my-app',
templateUrl: 'app/templates/app.html',
directives: [Grid],
providers: [ConfigService]
})
export class AppComponent {
(...)
}
快速的解决方案是删除网格组件的 providers
属性...这样服务实例将由 AppComponent
及其子组件共享。
另一种解决方案是在bootstrap
函数中注册相应的提供程序。在这种情况下,实例将由整个应用程序共享。
bootstrap(AppComponent, [ ConfigService ]);
要理解为什么需要这样做,您需要了解 Angular2 的“分层注入(inject)器”功能。以下链接可能会有用:
关于typescript - Angular2 - 使用服务在组件之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273106/