2的组件之间共享数据

2的组件之间共享数据

本文介绍了如何在Angular 2的组件之间共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 1.x.x中,您只要求提供相同的服务,并且最终获得相同的实例,从而可以在服务中共享数据.

In Angular 1.x.x you simply ask for the same service and you end up with the same instance, making it possible to share the data in the service.

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

Now in Angular 2 I have a component that has a reference to my service. I can read and modify the data in the service, which is good. When I try to inject the same service in another component, it seems as if I get a new instance.

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

What am I doing wrong? Is it the pattern itself that is wrong (using a service to share data) or do I need to mark the service as a singleton (within one instance of the app) or something?

我在2.0.0-alpha.27/ btw

我通过@Component批注中的appInjector(现在为providers)注入服务,然后将引用保存在构造函数中.它在组件中本地工作-只是不像我想的那样跨组件(它们不共享相同的服务实例).

I inject a service through appInjector (edit: now providers) in the @Component annotation and then save a reference in the constructor. It works locally in the component - just not across components (they do not share the same service instance) like I thought they would.

更新:从Angular 2.0.0开始,我们现在有了@ngModule,您可以在该@ngModuleproviders属性下定义服务.这将确保将该服务的相同实例传递到该模块中的每个组件,服务等. https://angular.io/docs/ts/latest/guide/ngmodule .html#providers

UPDATE: As of Angular 2.0.0 we now have @ngModule where you would define the service under the providers property on said @ngModule. That will ensure the same instance of that service to be passed to each component, service, etc. in that module.https://angular.io/docs/ts/latest/guide/ngmodule.html#providers

更新:总体而言,Angular和FE开发发生了很多事情.正如@noririco所提到的,您还可以使用像NgRx这样的状态管理系统: https://ngrx.io/

UPDATE: A lot has happened to Angular and FE development in general. As @noririco mentioned, you could also use a state management system like NgRx:https://ngrx.io/

推荐答案

服务单例是一个很好的解决方案.其他方式-data/events bindings.

A service singleton is a nice solution. Other way - data/events bindings.

以下是这两个示例:

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 2的组件之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:17