Angular OnPush 未更新模板

Angular OnPush not updating template

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

this.accountLoading true

其次是:

this.accountLoading false

但是模板没有更新,并且一直认为 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();
}

HTML:

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

子组件:

打字稿:

@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. Have a read about it here https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb

如果您的两个组件都使用 OnPush 更改检测策略,则子模板不会在父模板更新时更新。您的子组件将需要实现 OnChanges 生命周期挂钩,当输入值发生变化时,您可以在那里触发变化检测。

我会用标准的可观察模式来做:

public accountLoading$: Observable<boolean>;

...

getAccount() {
   this.accountLoading$ = this.authStore
        .pipe(select(fromAuthStore.getAccountData), map(account => !!account));


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

HTML:

<child-component
  [accountLoading]="accountLoading$ | async">
</child-component>