gpt4 book ai didi

Angular OnPush 不更新模板

转载 作者:行者123 更新时间:2023-12-04 12:41:53 27 4
gpt4 key购买 nike

我有两个组件,都设置为 OnPush。调用 getAccount() 后,父组件将 accountLoading 设置为 true,然后在调用完成后将 accountLoading 设置为 false。正如预期的那样,控制台输出:

this.accountLoading true

其次是:

this.accountLoading false

但是模板没有更新,并且一直认为 accountLoading 是正确的。当值发生变化时,如何让模板按预期更新?我想将更改检测保留为 OnPush。

父组件:

typescript :

public accountLoading: boolean;
...

getAccount() {
this.accountLoading = true;
this.authStore
.pipe(select(fromAuthStore.getAccountData))
.subscribe(account => {
if (account) {
this.accountLoading = false;
}
console.log('this.accountLoading', this.accountLoading);
});

// Loading account if it hasn't yet been loaded
this.authService.getAccount();
}

HTML:

<child-component
[accountLoading]="accountLoading">
</child-component>

子组件:

typescript :

@Input() accountLoading: boolean;
...

HTML:

<p *ngIf="accountLoading">
Loading...
</p>

最佳答案

尝试一个行为主题

public accountLoading$: BehaviorSubject<boolean>(false);
...

getAccount() {
this.accountLoading$.next(true);
this.authStore
.pipe(select(fromAuthStore.getAccountData))
.subscribe(account => {
if (account) {
this.accountLoading$.next(false);
}
});

// Loading account if it hasn't yet been loaded
this.authService.getAccount();
}

并在模板中使用异步管道

<p *ngIf="accountLoading$ | async">
Loading...
</p>

我已经编写了一个库来为您处理很多此类状态管理,https://github.com/adriandavidbrand/ngx-rxcache .在这里阅读 https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb

关于Angular OnPush 不更新模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58073087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com