一种可能的解决方法是使用改变检测策略来触发组件的变化检测。在组件中的构造函数中将ChangeDetectorRef注入,然后使用它的detectChanges方法来手动触发变化检测。
示例代码:
import { Component, OnInit, AfterViewInit, ChangeDetectorRef } from '@angular/core'; import { ApiService } from '../api.service';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponentComponent implements OnInit, AfterViewInit {
data: any[];
constructor(private apiService: ApiService, private cdRef: ChangeDetectorRef) { }
ngOnInit() { this.apiService.getData().subscribe(data => { this.data = data; }); }
ngAfterViewInit() { this.cdRef.detectChanges(); } }
在上面的代码中,ngAfterViewInit方法会在视图初始化之后调用,然后我们可以使用ChangeDetectorRef来手动触发变化检测,以确保数据已经被显示在html页面上。
上一篇:API数据验证的最佳实践