angular - 不明白为什么我的 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);
});
解决方案
在构建管道时,this.apiService.getApiData()
它不在箭头函数中,而是立即执行。调用作为参数传递并不重要。该表达式将像任何其他 JS 调用一样执行(尝试放在console.log
同一个地方)。
您可以这样做.concatMap(userData => this.apiService.getApiData().map(apidata => {userData, apiData}))
(或switchMap
),但这会始终调用 API。我不知道什么最适合您的需求。
推荐阅读
- python - 安装和配置 GeoDjango 的问题
- sql-server - 在 Visual Studio (SQL Server) 中返回标识值
- string - 显示当前日期的所有记录 - Hive 中的 1
- ios - 在旧版本 Xcode 上开发并在 Xcode 12.5 上重新打开的项目中构建错误?
- angular - 角度 - 设置器不更新重复值
- java - Java多维数组 - 如何从常规数组元素创建多维数组
- python - python/pandas - MultiIndexing - 消除全局变量的使用
- javascript - 使用 express 和 socket.io 的简单节点客户端服务器通信不起作用
- xamarin.forms - 如何修复 Xamarin Forms 管道目标框架错误
- javascript - 如何将 CSS 子类转换为样式化组件