Angular5 从 observable 获取数据到组件
Angular5 Getting data from observable to component
我尝试将数据从 observable 获取到组件。
我无法将数据放入打字稿中的数组中,我仍然得到 Observable 对象和负类型的消息。但是,在 HTML 中,循环正确地打印了来的数据。
服务:
@Injectable()
export class DataService {
private _dataListSource: BehaviorSubject<Data[]> = new BehaviorSubject<Data[]>([]);
constructor(private http: HttpClient) {
}
getDataList(): Observable<any> {
return this.http.get<Data[]>('/rest/data/lastDatas').map(res => {
this._dataListSource.next(res);
console.log(res);
});
}
subscribeToDatas(): Observable<Data[]> {
return this._dataListSource.asObservable().distinctUntilChanged();
}
getData(): Observable<Data[]> {
return this.http.get<Data[]>('/rest/data/lastDatas');
}
}
TypeScript class:
export class DataComponent implements OnInit {
dataStatuses: Data[];
public dataList$: Observable<Data[]>;
constructor(public dataService: DataService) {
}
ngOnInit() {
this.dataList$ = this.dataService.subscribeToDatas();
this.dataService.getDataList().subscribe();
console.log("Informacja ", this.dataList$);
}
}
HTML :
<div *ngIf="dataList$ | async; let dataList; ">
<div *ngFor="let data of dataList">
{{data.id}}
</div>
</div>
您的 dataList$
return 是 Observable
,这是正确的。 html 仍然有效,因为您使用的是 async
pipe,它会自动在 HTML.
中为您执行 "subscribe" 部分
如果您想查看 dataList$
return 的内容,只需订阅即可:
this.dataList$.subscribe(data=>{
console.log("data from dataList! ",data);
})
我尝试将数据从 observable 获取到组件。
我无法将数据放入打字稿中的数组中,我仍然得到 Observable 对象和负类型的消息。但是,在 HTML 中,循环正确地打印了来的数据。
服务:
@Injectable()
export class DataService {
private _dataListSource: BehaviorSubject<Data[]> = new BehaviorSubject<Data[]>([]);
constructor(private http: HttpClient) {
}
getDataList(): Observable<any> {
return this.http.get<Data[]>('/rest/data/lastDatas').map(res => {
this._dataListSource.next(res);
console.log(res);
});
}
subscribeToDatas(): Observable<Data[]> {
return this._dataListSource.asObservable().distinctUntilChanged();
}
getData(): Observable<Data[]> {
return this.http.get<Data[]>('/rest/data/lastDatas');
}
}
TypeScript class:
export class DataComponent implements OnInit {
dataStatuses: Data[];
public dataList$: Observable<Data[]>;
constructor(public dataService: DataService) {
}
ngOnInit() {
this.dataList$ = this.dataService.subscribeToDatas();
this.dataService.getDataList().subscribe();
console.log("Informacja ", this.dataList$);
}
}
HTML :
<div *ngIf="dataList$ | async; let dataList; ">
<div *ngFor="let data of dataList">
{{data.id}}
</div>
</div>
您的 dataList$
return 是 Observable
,这是正确的。 html 仍然有效,因为您使用的是 async
pipe,它会自动在 HTML.
如果您想查看 dataList$
return 的内容,只需订阅即可:
this.dataList$.subscribe(data=>{
console.log("data from dataList! ",data);
})