首页 > 解决方案 > 如何避免两次调用观察方法?

问题描述

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被调用时。

我该如何解决这个问题?

标签: angular

解决方案


你可以尝试使用额外的变量

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">

推荐阅读