javascript - 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
.
解决方案
您可以将组件 changeDetectionStrategy 更改为 onPush。之后,您的 doSomething 函数不会多次调用。所以基本上它在检测到更改时调用该函数,这就是它多次调用的原因,所以在更改检测技术后不会发生
尝试这个:
在您的组件中:
class Component implements OnInit {
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush // this line
})
}
推荐阅读
- macos - 在 OSX 上交叉编译 MIPS MT7688 OpenWRT (mipsel-unknown-linux-musl)
- pandas - 如何在选择结果中强制标题顺序?
- reactjs - react-native 将数据从第二个导航传递给父导航
- python-3.x - 如何并行迭代两个不同的列表,收敛到一个
- python - 通过python中的线程访问导入模块的locals()
- css - React-Native 文本不在两行上
- javascript - 即使在 Firefox 中更改,也会自动上传本地文件
- ios - 将图像保存到特定相册,但限制保存到相机胶卷文件夹
- mongodb - 使用会话的官方 mongo-go-driver
- imagemagick - Imagemagick FailedToExecuteCommand `"gswin32c.exe"