我有一個角2的服務,從API 這項服務3名的訂戶(在組件中所定義的)取數據各做與數據別的東西(不同的圖形)角2可觀察到與多個訂戶
我注意到我正在對API執行三個GET請求,而我想實現的是一個請求並且訂閱者將共享數據 我已經研究了HOT和COLD observable,並嘗試了可觀察對象上的.share()我還在做3個人電話
更新,插入代碼
服務
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { StationCompliance } from './model/StationCompliance';
@Injectable()
export class StationComplianceService {
private url = '/api/read/stations';
constructor(private http : Http) {
console.log('Started Station compliance service');
}
getStationCompliance() : Observable<StationCompliance []> {
return this.http.get(this.url)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
}
}
組件1
import { Component, OnInit } from '@angular/core';
import { CHART_DIRECTIVES } from 'angular2-highcharts';
import { StationComplianceService } from '../station-compliance.service';
@Component({
selector: 'app-up-down-graph',
templateUrl: './up-down-graph.component.html',
styleUrls: ['./up-down-graph.component.css']
})
export class UpDownGraphComponent implements OnInit {
graphData;
errorMessage: string;
options;
constructor(private stationService : StationComplianceService) { }
ngOnInit() {
this.getStationTypes();
}
getStationTypes(){
this.stationService.getStationCompliance()
.subscribe(
graphData => {
this.graphData = graphData;
this.options = {
chart : {type: 'pie',
plotShadow: true
},
plotOptions : {
showInLegend: true
},
title : {text: 'Up and Down devices'},
series: [{
data: this.processStationType(this.graphData)
}]
}
},
error => this.errorMessage = <any>error
);
}
其他兩個組件幾乎相同,他們只是顯示其它圖形
感謝你的代碼真的幫了我 – naoru
我拉我的頭髮這個「問題」和這個職位讓我很快樂。謝謝 – sjosen
請考慮縮短解決方案:https://stackoverflow.com/questions/39627396/angular-2-observable-with-multiple-subscribers/48803113#48803113 – zeliboba