角度 2+ > 如何等待几个可观察变为可观察



在发送post请求之前,我尝试从用户那里获取IP(公共和私有((这两个功能运行良好(。这是我的问题,我没有实现在得到数据之前等待做帖子请求。。。

这是我的2个观察对象:

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)
}
});

我的另一个可观察到的被另一个模块调用来完成帖子请求:

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不是函数;。我尝试了很多东西,但似乎都不起作用。我需要帮助,因为我认为我误解了观察。。。

最后删除subscribe(),返回的是订阅,而不是getUserByToken函数中的可观察项。该错误是正确的,因为Subscription对象没有定义任何.pipe函数。

我认为问题出在你的ip_wan$上,你不需要从已经是可观察的东西创建observablehttp已经给了你一个,另一件事是你不应该把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)
);

最新更新