angular - 如何避免两次调用观察方法?
问题描述
API调用实现ngOnInit
如下:
ngOnInit() {
this.applicationObs = this.route.paramMap.pipe(
filter((params) => params.has('id')),
switchMap((params) => this.applicationService.getApplicationDetails(params.get('id'))),
map((data: ApplicationResponse) => data),
);
this.applicationObsSubscription = this.applicationObs.subscribe((response) => {
const fabricaSidebar = fabricApplicationSidebarMenu(response.application);
this.sidebarSections = fabricaSidebar.getSidebarMenuItems();
});
}
async
然后在我用来获取数据的模板中:
<ng-container *ngIf="applicationObs | async as app; else loading">
问题是它调用了两次,一次是 for async
,另一次是当subscribe
被调用时。
我该如何解决这个问题?
解决方案
你可以尝试使用额外的变量
applicationObs$ = new BehaviorSubject(null);
ngOnInit() {
this.applicationObs = this.route.paramMap.pipe(
filter((params) => params.has('id')),
switchMap((params) => this.applicationService.getApplicationDetails(params.get('id'))),
tap((data: ApplicationResponse) => this.applicationObs$.next(data)),
)
.subscribe((response) => {
const fabricaSidebar = fabricApplicationSidebarMenu(response.application);
this.sidebarSections = fabricaSidebar.getSidebarMenuItems();
})
}
<ng-container *ngIf="applicationObs$ | async as app; else loading">
推荐阅读
- cookies - 使用 Sustainsys.Saml2 的 400 错误请求标头或 Cookie 太大
- firebase - 获取请求令牌失败。授权完成但出现错误。带有颤振和火力的 Twitter API
- c++ - 在 C++ 中,所有非成员函数指针的大小是否相同
- c# - 为什么 T : IMyInterface 在 C# 中工作,但 IMyInterface 不工作?
- gradle - Intellij如何设置gradle属性-Pname=value
- linux - 使用 vim 扩展 (vscodevim) 评论 VSCode
- amazon-eks - 代理公共没有出现在 AWS EKS 中
- c - K&R C 第 2 章赋值运算符和表达式
- javascript - 增加对象中的值
- javascript - push 不是一个函数 javascript