div*_*mod 5 observable rxjs angular
我对rxjs很新.
我试图创建一个运行角度2 http请求的函数,如下所示:
syncFromApi$() {
// create Headers
...
let ob$ = this.http.post(
CONFIG_APP.apiEndpoint + '/sync/app',
'',
{ headers: headers }
)
.map((response:Response) => {
return Observable.of({type: "success", payload: response.json()});
})
.catch(function (err:Response) {
return Observable.of({type: "error", payload: err.json()});
});
return ob$;
}
Run Code Online (Sandbox Code Playgroud)
简而言之,当成功时,我返回一个Object,表示请求是否成功.之后,我想根据返回的对象切换地图:
let o$ = syncFromApi$()
.switchMap((value) => {
console.log("value", JSON.stringify(value, null, 0));
if (data.type === 'success') {
return Observable.of(1);
} else if (data.type === 'error') {
return Observable.of(2);
}
});
Run Code Online (Sandbox Code Playgroud)
这就是我面临的问题.console.log(...)输出如下对象:
value, {"_isScalar": true, "value": THIS_IS_WHAT_I_NEED_AS_VALUE, "scheduler": null}
Run Code Online (Sandbox Code Playgroud)
但我只需要使用syncFromApi $函数返回的对象.
如果我observable.of()以错误的方式使用,有人可以向我解释一下吗?
我试过observable.of(1),它返回1作为值.如果我使用一个对象(observable.of({ type: "myType", message: "myMessage" })),它返回一个对象包装我需要用钥匙"_isScalar","价值"和"调度"的对象.
提前致谢.
Thi*_*ier 13
您的问题在于您的map运营商:
let ob$ = this.http.post(
CONFIG_APP.apiEndpoint + '/sync/app',
'',
{ headers: headers }
)
.map((response:Response) => {
return {type: "success", payload: response.json()}; // <----
})
Run Code Online (Sandbox Code Playgroud)
您需要返回一个不是可观察对象的对象.该map运营商使用对象喜欢它,并不会突出返回的可观测到的可观察链.
如果Observable.of由于某些原因想要返回,则需要使用flatMap运算符:
let ob$ = this.http.post(
CONFIG_APP.apiEndpoint + '/sync/app',
'',
{ headers: headers }
)
.flatMap((response:Response) => {
return Observable.of({type: "success", payload: response.json()});
})
Run Code Online (Sandbox Code Playgroud)
这对于catch运算符来说很好,因为它期望将observable返回到其关联的回调中.
| 归档时间: |
|
| 查看次数: |
18245 次 |
| 最近记录: |