角度 2+ >条件可观察映射



我尝试对几个Observable进行条件映射。首先,我想做一个请求,看看我是否需要获得IP。如果是真的,我会在发送Post Request之前得到Ip。

这是我的2个观察对象:

// NEED IP
this.init$ = this.http.get(API_URL + '/init').pipe(
tap((response: any) => {
this.init_need_ip = response.need_ip
})
);
// IP WAN
this.ip_wan$ = this.http.get("https://api.ipify.org/?format=json").pipe(
tap((response: any) => { this.ip_wan = response.ip })
);

我的行动:

getIp(model, url, params, options = {}): Observable<any> {
return this.init$.pipe(
concatMap(() => {
if (this.init_need_ip) {
this.ip_wan$;
}
}),
concatMap(() => {
return this.http.post<{model}>(url, JSON.stringify(Object.assign({}, params, {ip_wan: this.ip_wan, ip_lan: JSON.stringify(this.ip_lan)})), options);
}),
);

}

但我有一个错误:

类型为'((=>的参数;void"不可分配给类型的参数'(值:任意,索引:数字(=>ObservableInput。键入"void"不可分配给类型"ObservableInput"。

如果我试图在我的其他文件中返回一些东西,比如:

return this.init$.pipe(
concatMap(() => {
if (this.init_need_ip) {
this.ip_wan$;
} else {
return of(null);
}
}),
concatMap(() => {
return this.http.post<{model}>(url, JSON.stringify(Object.assign({}, params, {ip_wan: this.ip_wan, ip_lan: JSON.stringify(this.ip_lan)})), options);
}),
);

我从调用函数的服务中得到了另一个错误:

TypeError:您在需要流的地方提供了"undefined"。你可以提供Observable、Promise、Array或Iterable。

如果其他地方不需要,我建议通过管道传递数据,而不是将其分配给组件的属性。

如果我正确理解你的代码,我认为你应该能够做这样的事情:


const init$ = this.http.get('/init');
const ip$ = this.http.get("https://api.ipify.org/?format=json");
init$.pipe(
switchMap(response => {
if(response.need_ip){
return ip$;
}else{
return of({})
}
}),
switchMap(response => {
return this.http.post<{model}>(
url, 
JSON.stringify({
...params, 
ip_wan: response.ip_wan,
ip_lan: JSON.stringify(this.ip_lan),
}),
options
);
})
)

理想情况下,您应该有一个带有此API调用的服务,并按如下方式使用它:

this.ipService.init().pipe(
switchMap(response => response.need_ip ? this.ipService.getIp() : of({})),
switchMap(response => this.ipService.register(response.ip_wan, this.ip_lan))
)

最新更新