【发布时间】:2019-08-29 20:00:14
【问题描述】:
如果我在一个 observable 上使用 tap rxjs 运算符来调用另一个 observable,我能保证它在管道的其余部分之前完成吗?
这里的想法是让服务对后端进行 http 调用,如果登录良好,则创建一个 cookie,然后将映射的响应返回给消费组件。我想确保在继续确保没有竞争条件之前添加了 cookie。
import { of, Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
const httpObservable = loginAccount('fsdfds', 'fdsfsd');
httpObservable.subscribe(x => {
console.log(x);
});
function loginAccount(username, password): Observable<any> {
const httpResponse = of({ loggedIn: false, data: 'faketokenfrombackend' });
return httpResponse.pipe(
// Will this AWLAYS complete before map?
tap(resp => fakeLocalStorage('Do something with the result')),
// Will this AWLAYS complete before map?
tap(resp => fakeLocalStorage('Do something else with the result')),
map(resp => {
if (!resp.loggedIn)
return { success: false, message: 'really bad thing happened' };
else
return {success: true, message: 'WEEEEEE, it worked!'}
}));
}
function fakeLocalStorage(data: string): Observable<boolean> {
console.log('adding token to cookie');
return of(true);
}
上述脚本按预期将其输出到控制台窗口,但我可以依赖它吗?
adding token to cookie
adding token to cookie
{success: false, message: "really bad thing happened"}
【问题讨论】:
标签: javascript typescript rxjs