javascript - Angular 2中如何在组件间正确共享服务数据

标签 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));
  });
}

实际.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 文件时,我想要一个解决方案,将此信息保存在服务中并与多个订阅者共享。

最佳答案

那是因为

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

要在 Controller /组件之间共享数据并仅创建单个实例,您必须将您的服务注入(inject)bootstrap 函数

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

}

这是你应该做的。

关于javascript - Angular 2中如何在组件间正确共享服务数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37727990/

相关文章:

javascript - 为什么我的 RestFul API 与express和nodejs每天都会崩溃?

angular - 当组件由 router-outlet 创建时,如何为组件设置输入绑定(bind)?

delphi - 如何 "scan"当前安装的 VCL 组件的完整列表

angular - Firestore 使用哪种数据类型作为时间戳?

java - 重绘用作背景的 JPanel 时如何保持其他组件在前面?

javascript - Aurelia:自定义元素未按预期呈现输出。浏览器不加载js文件。

javascript - react js : How to Get Automatically Logout After Session Expired?

javascript - 基于 React Router 过滤映射对象

javascript - Bootstrap 模态重叠

javascript - Angular 2 中的表格