如何在Angular 2

时间:2016-06-09 13:55:24

标签: javascript angular components observers

我想创建一个服务,从.json文件中获取一次数据并将其共享给多个订阅者。但现在我的解决方案从.json文件获取数据的请求数等于我服务的一些子文件。

getconfig.service.ts



import {Injectable} from 'angular2/core';
import {Http, Response} from "angular2/http";

@Injectable()
export class ConfigService {
    config: any;
    http: Http;

    constructor(http: Http) {
        this.http = http;
        console.log('Inside service');
        this.config = this.http.get('/config.json');
    }

}




robotui.component.ts



...
import {ConnectionService} from '../services/connection.service';

@Component({
  ...
  providers: [HTTP_PROVIDERS, ConfigService, ConnectionService]
  ...
})

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({
  ...
  providers: [ConfigService]
})

export class ActualPhotoComponent {

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

}




当我在我的控制台中运行时,我看到:

enter image description here

因此,每个子纤维都有请求。当我只获得一次config.json文件时,我想要一个解决方案,将此信息保存在服务中并与多个子文件共享。

1 个答案:

答案 0 :(得分:4)

那是因为

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

要在控制器/组件之间共享数据并仅创建单个实例,您必须将服务注入bootstrap function

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

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

在订阅组件中,

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

}

这是你应该做的。