typescript – Angular2 – 使用服务在组件之间共享数据

前端之家收集整理的这篇文章主要介绍了typescript – Angular2 – 使用服务在组件之间共享数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个对象,我想在我的组件之间共享一个Angular2应用程序.

这是第一个组件的来源:

@H_301_3@/* app.component.ts */ // ...imports import {ConfigService} from './config.service'; @Component({ selector: 'my-app',templateUrl: 'app/templates/app.html',directives: [Grid],providers: [ConfigService] }) export class AppComponent { public size: number; public square: number; constructor(_configService: ConfigService) { this.size = 16; this.square = Math.sqrt(this.size); // Here I call the service to put my data _configService.setOption('size',this.size); _configService.setOption('square',this.square); } }

第二部分:

@H_301_3@/* grid.component.ts */ // ...imports import {ConfigService} from './config.service'; @Component({ selector: 'grid',templateUrl: 'app/templates/grid.html',providers: [ConfigService] }) export class Grid { public config; public header = []; constructor(_configService: ConfigService) { // issue is here,the _configService.getConfig() get an empty object // but I had filled it just before this.config = _configService.getConfig(); } }

最后我的小服务,ConfigService:

@H_301_3@/* config.service.ts */ import {Injectable} from 'angular2/core'; @Injectable() export class ConfigService { private config = {}; setOption(option,value) { this.config[option] = value; } getConfig() { return this.config; } }

我的数据不是共享的,在grid.component.ts中,_configService.getConfig()行返回一个空对象,但它在app.component.ts之前被填充.

我阅读了文档和教程,没有任何工作.

我失踪了什么

谢谢

解决

我的问题是我正在注入我的ConfigService两次.在应用程序的引导和在我使用它的文件中.

删除了提供者的设置和它的工作!

您可以在两个组件中定义它.所以服务不共享.您有一个AppComponent组件实例,另一个用于Grid组件. @H_301_3@@Component({ selector: 'my-app',providers: [ConfigService] }) export class AppComponent { (...) }

快速解决方案是删除提供者属性到您的网格组件…这样,服务实例将被AppComponent及其子组件共享.

另一个解决方案是在引导功能注册相应的提供者.在这种情况下,实例将被整个应用程序共享.

@H_301_3@bootstrap(AppComponent,[ ConfigService ]);

要理解为什么需要这样做,您需要注意Angular2的“分层注射器”功能.以下链接可能会有用:

> What’s the best way to inject one service into another in angular 2 (Beta)?
> https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html

猜你在找的Angularjs相关文章