在 Angular 1.x.x 中,您只需请求相同的服务并最终得到相同的实例,从而可以在服务中共享数据。
现在在 Angular 2 中,我有一个组件引用了我的服务。我可以读取和修改服务中的数据,这很好。当我尝试在另一个组件中注入(inject)相同的服务时,我似乎获得了一个新实例。
我做错了什么?是模式本身错误(使用服务共享数据)还是我需要将服务标记为单例(在应用程序的一个实例中)或其他?
我在 2.0.0-alpha.27/
顺便说一句
我通过 appInjector
(编辑:now providers
)在 @Component
注释中注入(inject)一个服务,然后在构造函数中保存一个引用。它在组件中本地工作——只是不像我想象的那样跨组件(它们不共享相同的服务实例)。
更新:从 Angular 2.0.0 开始,我们现在有了 @ngModule,您可以在 @ngModule
的 providers
属性下定义服务>。这将确保将该服务的相同实例传递给该模块中的每个组件、服务等。
https://angular.io/docs/ts/latest/guide/ngmodule.html#providers
更新:Angular 和 FE 开发总体上发生了很多变化。正如@noririco 提到的,您还可以使用像 NgRx 这样的状态管理系统: https://ngrx.io/
最佳答案
服务单例是一个不错的解决方案。其他方式 - 数据/事件绑定(bind)
。
下面是两者的例子:
class BazService{
n: number = 0;
inc(){
this.n++;
}
}
@Component({
selector: 'foo'
})
@View({
template: `<button (click)="foobaz.inc()">Foo {{ foobaz.n }}</button>`
})
class FooComponent{
constructor(foobaz: BazService){
this.foobaz = foobaz;
}
}
@Component({
selector: 'bar',
properties: ['prop']
})
@View({
template: `<button (click)="barbaz.inc()">Bar {{ barbaz.n }}, Foo {{ prop.foobaz.n }}</button>`
})
class BarComponent{
constructor(barbaz: BazService){
this.barbaz = barbaz;
}
}
@Component({
selector: 'app',
viewInjector: [BazService]
})
@View({
template: `
<foo #f></foo>
<bar [prop]="f"></bar>
`,
directives: [FooComponent, BarComponent]
})
class AppComponent{}
bootstrap(AppComponent);
关于angular - 我如何在 Angular 2 中的组件之间共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026886/