问题可能是由于 Angular 的变更检测机制导致的。为了解决这个问题,我们可以尝试使用 Angular 的 ChangeDetectorRef 服务并手动触发变更检测。
首先,在组件构造函数中注入 ChangeDetectorRef 服务:
constructor(private changeDetectorRef: ChangeDetectorRef) {}
然后,在点击事件的 subscribe 回调函数中,使用 ChangeDetectorRef 的 detectChanges 方法:
onClick() {
this.http.get('url').subscribe(response => {
this.data = response;
this.changeDetectorRef.detectChanges(); // 手动触发变更检测
});
}
这样,当订阅回调中的数据发生变化时,视图也会随之更新。
另外,如果我们使用了 async 管道,也可以尝试使用 ChangeDetectorRef 的 markForCheck 方法来手动触发变更检测。例如:
{{ data | async }}
onClick() {
this.http.get('url').subscribe(response => {
this.data = of(response).pipe(delay(1000));
this.changeDetectorRef.markForCheck(); // 手动触发变更检测
});
}
这样,当订阅回调中的数据发生变化时,视图也会随之更新。