【发布时间】:2018-05-04 09:45:41
【问题描述】:
我慢慢开始掌握 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);
});
【问题讨论】: