Angular 服务时组件未更新 returns

Angular component not updating when service returns

我有一个 Angular 组件,在某些图标上带有徽章。徽章的数字来自我在进入页面时在 ionViewWillEnter() 中调用的 api。当 api returns 时,结果被分配给一个局部变量,然后在标记中引用该变量。 在Chrome桌面上,一切正常。在 Chrome android 中,徽章只有在我触摸屏幕后才会出现。 为什么对局部变量的更改不会立即反映在标记中?我试过将整个例程放在 NgZone 中,但无济于事。我还研究了 ChangeDetectorRef.detectChanges()markForCheck()ApplicationRef.tick()

中的建议

更新 2: 数据作为 object 向下传递到 child 组件,然后通过 @Input 属性作为原语再次传递到 grandchild。如果我还在 parent 的标记中直接显示信息,那么 parent 和 grandchild 组件都会在调用服务 returns 时按预期更新。如果我试图通过将 display:none 放在 parent 上来欺骗系统,我的问题 returns 并且我必须触摸屏幕才能看到 child 中的变化。

这是我的 .ts 代码...

// declaration
pastilles: Pastilles = { nbFraisCarte: 0, nbFraisRefuse: 0, nbJustificatifs: 0 };

async ionViewWillEnter(){
  this.ngZone.run(async () => {
    await this._myService
      .pastilles()
      .toPromise()
      .then((resp) => {
        if ((resp.status = 'success')) {
          this.pastilles= resp.sData;
        }
      });
  });
}

在 child 组件中,我有...

@Input()
pastilles: Pastilles;

然后在标记中...

<tne-round-button
  (click)="createFraisFrom.emit('justificatif')"
  icon="image"
  [pastille]="pastilles.nbJustificatifs"
></tne-round-button>

然后在 tne-round-button grandchild 中,大同小异...

@Input()
pastille: number;

和标记...

<div class="pastille" *ngIf="pastille">
  <div class="pastille-text">{{ pastille }}</div>
</div>

我错过了什么?

因为 pastilles 是一个对象,并且 Angular 无法判断对象已经更改,因为它的引用仍然相同,请尝试这样做。

this.pastilles = { ...resp.sData }

或者这个

Object.assign(this.pastilles, resp.sData);

我会在 NgZone 中试用它们。让我知道它是否有效!

好吧,这几乎让我心碎。事实证明,问题出在子组件中使用了数据,而根本没有对子组件进行更新。解决方法是直接在接收它的组件的模板中使用数据,从而触发刷新。我在父模板中添加了一个不可见的 div,像这样...

<div style="visibility: hidden;">{{pastilles.nbJustificatifs}}</div>

...徽章,仍然在我的子组件中处理,神奇地出现了。这很丑陋,但我继续前进!