gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:48:27 25 4
gpt4 key购买 nike

我想创建一个服务来一次从 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com