如何共享部件之间的数据Angular2? [英] How do i share data between components in Angular2?

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

问题描述

在角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.

现在在角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

我注入到 appInjector (编辑:现在 viewInjector )服务在 @组件注释,然后保存在构造函数的引用。它的工作原理在本地的组件 - 只是不跨组件(它们不共享相同的服务实例)就像我认为他们会

I inject a service through appInjector (edit: now viewInjector) 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.

推荐答案

服务单是一个很好的解决方案。另一种方式 - 数据/事件的绑定。这里是两者的一个例子:

Service singleton is a nice solution. Other way - data/events bindings. Here is an example of both:

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);

观看直播

这篇关于如何共享部件之间的数据Angular2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆