Angular OnPush 不更新模板

Bre*_*ett 3 angular angular-changedetection

我有两个组件,它们都设置为OnPush. 父组件集accountLoading为true,一旦getAccount()被调用,然后设置accountLoading为false,一旦完成呼叫。正如预期的那样,控制台输出:

this.accountLoading 真

其次是:

this.accountLoading 假

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

父组件:

打字稿:

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();
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<child-component
  [accountLoading]="accountLoading">
</child-component>
Run Code Online (Sandbox Code Playgroud)

子组件

打字稿:

@Input() accountLoading: boolean;
...
Run Code Online (Sandbox Code Playgroud)

HTML:

<p *ngIf="accountLoading">
  Loading...
</p>
Run Code Online (Sandbox Code Playgroud)

Adr*_*and 5

尝试行为主题

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();
}
Run Code Online (Sandbox Code Playgroud)

并在模板中使用异步管道

<p *ngIf="accountLoading$ | async">
  Loading...
</p>
Run Code Online (Sandbox Code Playgroud)

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