我有一个angular2应用程序,其服务使得具有各种订阅者的HTTP调用(每个都显示不同的信息)。 第一次调用完成后,我需要进行第二次独立的HTTP调用,并根据检索到的值过滤从第一次调用中获得的数组。 它没有用,第二个HTTP调用的用户,不知道等待,我得到一个空列表,因为第一个调用的数组还没有
我附上相关服务
constructor(private http: Http) {
this.initializeAlertService();
console.log('Started alerts service');
}
initializeAlertService() {
if (!this.allData$) {
this.allData$ = <BehaviorSubject<Alert[]>> new BehaviorSubject(new Array<Alert>());
this.http.get(this.url)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error || 'Server Error'))
.subscribe(
allData => {
this.allData = allData;
this.allData$.next(allData);
this.initializeAlertSeverities(); -- I want this to fire when the 'allData' is ready
},
error => console.log("Error subscribing to AlertService: " + error)
);
}
}
subscribeToAlertSeverities(): Observable<AlertSeverity[]> {
return this.alertSeverities$.asObservable();
}
然后在我的组件上我订阅了alertSeverities,但我得不到数据......
答案 0 :(得分:0)
我能够通过将http调用的结果传递给代码的订阅部分中的函数来解决这个问题
constructor(private http: Http) {
this.initializeAlertService();
console.log('Started alerts service');
}
initializeAlertService() {
if (!this.alerts$) {
this.alerts$ = <BehaviorSubject<Alert[]>> new BehaviorSubject(new Array<Alert>());
this.alertSeverities$ = <BehaviorSubject<AlertSeverity[]>> new BehaviorSubject(new Array<AlertSeverity>());
this.http.get('first url')
.map((res:Response) => res.json())
.subscribe(alerts => {
this.alerts$.next(alerts);
this.initializeAlertSeverities(alerts);
})
}
}
initializeAlertSeverities(alerts){
this.http.get('second url')
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error || 'Server Error'))
.subscribe(
severities => {
severities.map((severity) => {
var severityCounter = alerts.filter(alert => alert['severity'] == severity.severityValue).length;
severity.severityCount = severityCounter;
});
this.alertSeverities$.next(severities);
},
error => console.log("Error subscribing to Alert Severities: " + error)
);
}
subscribeToAlertSeverities(): Observable<AlertSeverity[]> {
//actual subscriber that components subscribe to
return this.alertSeverities$.asObservable();
}
subscribeToAlertService(): Observable<Alert[]> {
return this.alerts$.asObservable();
}