首页 > 解决方案 > asyncPipe 中的方法运行多次

问题描述

我正在使用asyncPipe一个*ngIf装饰器,该装饰器会自动订阅/取消订阅一个object<ng-container>...</ng-container>.

到目前为止一切顺利,但在ng-container标签内,我想将object作为参数传递给方法doSomething(object)

问题是该方法运行了 5-8 次?

HTML 模板

<ng-container *ngIf="(user$ | async) as user">
   {{  doSomething(user) }} <-- method executes multiple times
</ng-container

打字稿文件

class Component implements OnInit { 

    user: Observable<User>; 

    constructor() {}

    ngOnInit() {
        this.user$ = this.userService.getUser(id);
    }

    checkConfigs(object) {
        console.log(object);
    }
}

我已经测试过问题是否是多次执行但运行一次的 Observable。然后认为其中的代码ng-container是问题所在,但这也运行一次。

问题与不同,因为我不是在问它是否可取,而是在问如何解决这个问题。在实践中,这应该有效。但是由于 Angulars 的 changeDetection 架构,它在 Observables 中并不能像预期的那样工作,它甚至在本文中指出了你不知道的关于 AsyncPipe如何使用changeDetection: ChangeDetectionStrategy.OnPush.

标签: javascriptangulartypescriptasynchronous

解决方案


您可以将组件 changeDetectionStrategy 更改为 onPush。之后,您的 doSomething 函数不会多次调用。所以基本上它在检测到更改时调用该函数,这就是它多次调用的原因,所以在更改检测技术后不会发生

尝试这个:

在您的组件中:

class Component implements OnInit { 
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css'],
   changeDetection: ChangeDetectionStrategy.OnPush // this line
 })
}

推荐阅读