首页 > 解决方案 > 不明白为什么我的 withLatestFrom 运算符被触发

问题描述

我慢慢开始掌握 rxjs,但偶尔我会遇到一些让我困惑的事情。

在这种情况下,它与 withLatestFrom 运算符有关。下面的 rxjs 语句位于我的角度组件的 OnInit 方法中。当屏幕加载时,我看到 getApiData() 方法中的 api 调用被执行了两次,而我确信 userEventSubject$ 从未被触发(这就是为什么我有第一个点击运算符)。

我期望发生的是 getApiData() 方法仅在 userEventSubject$.next() 被调用时被调用,而在屏幕加载时永远不会被调用......

this.userEventSubject$
    .pipe(
        tap(creditNote => console.log('tapped!')),
        takeUntil(this.ngUnsubscribe$),
        filter(userEventData => this.checkValidity(userEventData)),
        withLatestFrom(this.apiService.getApiData()),
        mergeMap(([userEventData, apiData]) => {
            let modalRef = this.modalService.show(ModalDialogComponent, {
                initialState: { apiData }
            });
            let instance = <ModalDialogComponent>modalRef.content;

            return instance.save.pipe(
                mergeMap((info) =>
                    this.apiService.saveSomeData(userEventData, info).pipe(
                        catchError((error, caught) => {
                            instance.error = error;
                            return empty();
                        })
                    )
                ),
                tap(response => modalRef.hide())
            );
        })
    )
    .subscribe((response) => {
        this.handleResponse(response);
    });

固定版本:

this.userEventSubject$
    .pipe(
        tap(creditNote => console.log('tapped!')),
        takeUntil(this.ngUnsubscribe$),
        filter(userEventData => this.checkValidity(userEventData)),
        mergeMap(userEventData =>
            this.apiService.getApiData().pipe(
                map(data => {
                    return { userEventData, data };
                })
            )
        ),
        mergeMap(values => {
            let modalRef = this.modalService.show(ModalDialogComponent, {
                initialState: { data: values.apiData }
            });
            let instance = <ModalDialogComponent>modalRef.content;

            return instance.save.pipe(
                mergeMap((info) =>
                    this.apiService.saveSomeData(userEventData, info).pipe(
                        catchError((error, caught) => {
                            instance.error = error;
                            return empty();
                        })
                    )
                ),
                tap(response => modalRef.hide())
            );
        })
    )
    .subscribe((response) => {
        this.handleResponse(response);
    });

标签: angularrxjs5

解决方案


在构建管道时,this.apiService.getApiData()它不在箭头函数中,而是立即执行。调用作为参数传递并不重要。该表达式将像任何其他 JS 调用一样执行(尝试放在console.log同一个地方)。

您可以这样做.concatMap(userData => this.apiService.getApiData().map(apidata => {userData, apiData}))(或switchMap),但这会始终调用 API。我不知道什么最适合您的需求。


推荐阅读