如何在Angular 2的组件之间共享数据?

角度的 TypeScript

木嘢

2020-05-25

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

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

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

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

我通过注解中的appInjector(edit:now providers注入服务@Component,然后在构造函数中保存引用。它在组件中本地工作-只是没有跨组件(它们不共享相同的服务实例),就像我认为的那样。

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

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

第4177篇《如何在Angular 2的组件之间共享数据?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Me无敌 2020.05.25

在父组件模板中:

<hero-child [hero]="hero">
</hero-child>

在子组件中:

@Input() hero: Hero;

资料来源:https : //angular.io/docs/ts/latest/cookbook/component-communication.html

Itachi 2020.05.25

视情况是否简单而定

a) A -> B -> C A has two child B and C and if you want to share data between A and B or A and C then use (input / output)

If you want to share between B and C then also you can use (input / output) but it is suggested to use Service.

b) If the tree is big and complex. (if there are so many levels of parent and children connections.) And in this case if you want to share data then I would suggest ngrx

It implements the flux architecture which creates a client side store to which any component can subscribe and can update without creating any race condition.

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android