[英]Observable type with two http.get calls in Angular 2
在我的 ng2 服務中,我有一個有 2 個 http.get 調用的方法。 該函數看起來像這樣:
getInfo(userId: number): any {
this.http
.get(apiUrl, options)
.map(response => response.json())
.subscribe(example => {
this.example.FirstName = example.FirstName;
this.example.LastName = example.LastName;
this.http
.get(`/api/${userId}`)
.map(response => response.json())
.subscribe(example => {
this.example.Street = example.Street;
this.example.City = example.City;
return this.example;
});
});
}
唯一的問題是,在我的組件中,我無法訂閱此函數,因為它不是Observable<Example>
類型。
如果我用Observable<Example>
替換函數的類型 any ,我得到:
聲明類型既不是“void”也不是“any”的函數必須返回一個值
但是我確實在響應之后返回了一個值。
如果沒有兩個單獨的功能,我怎么能做到這一點?
是的,我確實檢查了這個答案: https : //stackoverflow.com/a/36712707/3264998
試着把它寫成你的方法體,這是一種方法,還有其他方法可以解決這個問題。
return this.http
.get(apiUrl, options)
.map(response => response.json())
.flatMap(example => {
this.example.FirstName = example.FirstName;
this.example.LastName = example.LastName;
return this.http
.get(`/api/${userId}`)
.map(response => {
let example =response.json();
this.example.Street = example.Street;
this.example.City = example.City;
return this.example;
});
});
我使用 rxjs/Rx flatMap 的解決方案:
import {Observable} from 'rxjs/Rx';
ngOnInit() {
const usersId = ['USR001', 'USR003'];
this.doRequest(usersId);
}
doRequest(queryArr, previousObservable = null) {
if (queryArr.length) {
const url = 'api/' + queryArr.shift();
let observable = null;
if (previousObservable) {
observable = previousObservable.flatMap(() => {
return this.http.get(url);
});
} else {
observable = this.http.get(url);
}
return this.doRequest(queryArr, observable);
} else {
return previousObservable;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.