出现这种情况的原因是由于Angular的变更检测机制不是自动更新整个应用程序的所有部分,而是只更新更改过的部分。如果服务响应后没有更新视图,这意味着Angular可能没有检测到更改。
要解决此问题,可以尝试以下方法:
import { Component, ChangeDetectorRef } from '@angular/core'; import { MyService } from './my.service';
@Component({
selector: 'my-component',
template:
})
export class MyComponent {
data: any;
constructor(private myService: MyService, private cd: ChangeDetectorRef) {}
ngOnInit() { this.myService.getData().subscribe( response => { this.data = response; this.cd.markForCheck(); }, error => { console.log(error); } ); } }
import { Component } from '@angular/core'; import { MyService } from './my.service';
@Component({
selector: 'my-component',
template:
})
export class MyComponent {
data: any;
constructor(private myService: MyService) {}
async ngOnInit() { try { const response = await this.myService.getData().toPromise(); this.data = response; } catch (error) { console.log(error); } } }
通过这些技巧,可以确保Angular应用程序在服务响应后更新视图,从而提高了用户体验。