angular - 我如何在 Angular 2 中的组件之间共享数据?

标签 angular typescript

在 Angular 1.x.x 中,您只需请求相同的服务并最终得到相同的实例,从而可以在服务中共享数据。

现在在 Angular 2 中,我有一个组件引用了我的服务。我可以读取和修改服务中的数据,这很好。当我尝试在另一个组件中注入(inject)相同的服务时,我似乎获得了一个新实例。

我做错了什么?是模式本身错误(使用服务共享数据)还是我需要将服务标记为单例(在应用程序的一个实例中)或其他?

我在 2.0.0-alpha.27/ 顺便说一句

我通过 appInjector(编辑:now providers)在 @Component 注释中注入(inject)一个服务,然后在构造函数中保存一个引用。它在组件中本地工作——只是不像我想象的那样跨组件(它们不共享相同的服务实例)。

更新:从 Angular 2.0.0 开始,我们现在有了 @ngModule,您可以在 @ngModuleproviders 属性下定义服务>。这将确保将该服务的相同实例传递给该模块中的每个组件、服务等。 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);

Watch live

关于angular - 我如何在 Angular 2 中的组件之间共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026886/

相关文章:

angular - 如何使用最大并行请求数发送 1000 个 XHTTP 请求

javascript - Angular2 + ng-bootstrap 示例

Angular 4 : Expected 0 type arguments, 但得到 1

css - 如何在 Angular 组件的样式标签中使用字符串插值?

angular - 如何在 Angular http 拦截器中抛出可观察到的错误

javascript - 如何在 Typescript 中编写 Kotlinesque 扩展函数?

Angular 5 标题服务未定义

javascript - 为 Angular 模板元素引用赋值的目的是什么?

typescript - 在 TypeScript 中获取 "HTMLInputElement"类型

javascript - 使用 typescript 3.1.3 将 React-Redux 调度定义为通用函数属性会引发错误