此问题可能是由于API返回的数据类型与所需数据类型不匹配所致。建议将API返回的数据转换为需要的类型,并使用Angular的ChangeDetectorRef来强制更新视图。
以下是代码示例:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-data',
template: `
{{ data }}
{{ loading }}
`
})
export class DataComponent implements OnInit {
data: any;
loading: boolean;
constructor(private apiService: ApiService, private cdRef: ChangeDetectorRef) {}
ngOnInit() {
this.loading = true;
this.apiService.getData().subscribe((response) => {
// Convert response data to required type
this.data = response.map(item => item.name);
// Trigger change detection to update view
this.cdRef.detectChanges();
this.loading = false;
});
}
}