原因是当ngFor在DOM中进行渲染时,订阅值仍未返回,因此ngFor没有可用的数据列表。可以使用RxJS的async管道,它会自动订阅并取消订阅。示例代码:
在组件.ts:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from './data.service';
@Component({
selector: 'app-component',
template: `
{{ item.name }}
`,
})
export class MyComponent implements OnInit, OnDestroy {
data$: Observable;
subscription: Subscription;
constructor(private dataService: DataService) {}
ngOnInit() {
this.data$ = this.dataService.getData();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
在服务.ts:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class DataService {
constructor(private http: HttpClient) {}
getData(): Observable {
return this.http.get('/api/data');
}
}