How to share service data between components correctly in Angular 2

喜欢而已 提交于 2019-12-07 03:19:27

That's because

@Component({
  ...
  providers: [ConfigService]  //<--- this creates service instance per component
})

To share data among controllers/components and to create single instance only, you have to inject your service into bootstrap function.

import {ConfigService } from './path to service';

bootstrap('AppCompoent',[configService])  //<----Inject here it will create a single instance only

In subscribing component,

robotui.component.ts

...
import {ConfigService} from '../services/getconfig.service';  //<----- Note this line here....
import {ConnectionService} from '../services/connection.service';

@Component({
  ...
  ...  // No providers needed anymore
  ...
})

constructor(private _configService: ConfigService) {
  this._configService.config.subscribe((observer) => {
    console.log('Subscribe in RobotUI component', JSON.parse(observer._body));
  });
}

actual.photo.component.ts

import {Component} from 'angular2/core';
import {ConfigService} from '../services/getconfig.service';

@Component({
  ...
  ...  // No providers needed anymore...
})

export class ActualPhotoComponent {

  constructor(private _configService: ConfigService) {
    this._configService.config.subscribe((observer) => {
      console.log('Subscribe in ActualPhoto component', JSON.parse(observer._body));
    });
  }

}

This is what you should do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!