kev*_*rsc 27 typescript angular2-services angular
我有一个对象,我想在我的组件之间共享一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
和第二部分:
/* 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();
}
}
Run Code Online (Sandbox Code Playgroud)
最后我的小服务,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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的数据没有被共享,在grid.component.ts中,该_configService.getConfig()行返回一个空对象,但它在app.component.ts之前就被填充了.
我阅读了文档和教程,没有任何效果.
我错过了什么?
谢谢
解决了
我的问题是我两次注入我的ConfigService.在应用程序的引导程序和我正在使用它的文件中.
我删除了providers设置,它的工作!
Thi*_*ier 28
您可以在两个组件中定义它.所以服务不是共享的.AppComponent组件有一个实例,组件有另一个实例Grid.
@Component({
selector: 'my-app',
templateUrl: 'app/templates/app.html',
directives: [Grid],
providers: [ConfigService]
})
export class AppComponent {
(...)
}
Run Code Online (Sandbox Code Playgroud)
快速解决方案是删除providersGrid组件的属性...这样,服务实例将AppComponent由其子组件共享.
另一种解决方案是在bootstrap函数内注册相应的提供者.在这种情况下,实例将由整个应用程序共享.
bootstrap(AppComponent, [ ConfigService ]);
Run Code Online (Sandbox Code Playgroud)
要了解为什么需要这样做,您需要了解Angular2的"分层注入器"功能.以下链接可能很有用:
对于最新版本的angular,如果要共享该服务,则无法将其添加到bootstrap函数中.只需将其添加到NgModule提供程序列表中,就像使用普通服务一样,其默认行为将是singleton.
自举(AppComponent);
@NgModule({
declarations: [
....
],
imports: [
....
],
providers: [
ConfigService,
....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32271 次 |
| 最近记录: |