[英]Angular 2+ > How to wait several Observable into Observable
在發送發布請求之前,我嘗試從用戶那里獲取 IP(公共和私有)(這兩個功能運行良好)。 這是我的問題,我沒有實現在獲取數據之前等待發布請求......
這是我的 2 個 Observables:
this.ip_wan$ = new Observable(observer => {
this.http.get("https://api.ipify.org/?format=json").subscribe((response: any) => {
this.ip_wan = response.ip;
observer.complete();
});
});
this.ip_lan$ = new Observable(observer => {
if (window.RTCPeerConnection) {
let ip = [];
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel('');
pc.createOffer(pc.setLocalDescription.bind(pc), noop);
pc.onicecandidate = function(event) {
if (event && event.candidate && event.candidate.candidate) {
var s = event.candidate.candidate.split('\n');
s.forEach(ip => {
this.ip_lan.push(ip.split(' ')[4])
});
observer.complete();
}
}.bind(this)
}
});
我的另一個由另一個模塊調用的 observable 來執行發布請求:
getUserByToken(token): Observable<UserModel> {
const httpHeaders = new HttpHeaders({
Authorization: `Bearer ${token}`,
});
return this.ip_wan$.pipe(
mergeMap(() => {
return this.ip_lan$.pipe(
concatMap(() => {
return this.http.post<UserModel>(API_URL, JSON.stringify({ ip_wan: this.ip_wan, ip_lan: JSON.stringify(this.ip_lan) }), { headers: httpHeaders });
}),
take(1),
)
}),
take(1),
).subscribe();
}
我收到此錯誤:“this.authHttpService.getUserByToken(...).pipe 不是函數”。 我嘗試了很多東西,但似乎沒有任何效果。 我需要幫助,因為我認為我誤解了 observable...
最后刪除subscribe()
,您將返回訂閱而不是getUserByToken
function 中的 observable。 錯誤是正確的,因為Subscription
object 沒有定義任何.pipe
function。
我認為問題在於您的ip_wan$
,您不需要從已經是可observable
的東西中創建可觀察的, http
已經給了您一個,另一件事是您以后不應該subscribe
可觀察的東西,您需要打開它,為此,只需pipe
如有必要,請嘗試以下操作:
// you don't subscribe here
this.ip_wan$ = this.http.get("https://api.ipify.org/?format=json").pipe(
tap((response: any) => this.ip_wan = response.ip)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.