【问题标题】:Observables inside of tap() completetap() 内部的 Observables 完成
【发布时间】: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


    【解决方案1】:

    是的,RxJS 会按顺序运行管道操作符。只要点击操作符是同步的,它们就会在地图操作符运行之前完成。如果他们做任何异步的事情,他们就不会。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多