【发布时间】:2020-07-29 13:08:03
【问题描述】:
考虑:
this.getList().subscribe((data) => {
console.log("data", data);
this.listItems = data;});
以上是我从中返回可观察对象的方法。
【问题讨论】:
-
上帝的一天!请参考我的回答。这是链接:enter link description here
考虑:
this.getList().subscribe((data) => {
console.log("data", data);
this.listItems = data;});
以上是我从中返回可观察对象的方法。
【问题讨论】:
试试这个,将 observable 分配给组件属性
listItems$ = this.getList();
然后使用异步管道订阅模板中的 observable。
<ng-container *ngIf="listItems$ | async as listItems">
{{ listItems | json }}
</ng-container>
无需管理订阅。
【讨论】:
上述方法应该有效。我建议在分配后记录 this.listItems 以仔细检查您是否不确定。
您可能遇到的问题是它的运行顺序。请记住,这是异步发生的,所以 listItems 会在所有其他正常组件发生后被分配。
我经常使用的一个解决方案(假设您的模板引用了数据)是将整个模板(或无论如何使用数据的区域)保存在 ngIf 中:
*ngIf="this.listItems"
这样模板只有在订阅完成后才会显示。
【讨论】:
推荐的方式是不要订阅内部组件类(.ts),而是使用可观察的。
listItems$ = this.getList(); // I agree with Adrian Brand
模板:(假设您使用表格)
<table>
<tr *ngFor="let item of listItems$ | async;"> // async handles unsubscribe by itself.
<td>{{ item.name }}</td>
</tr>
<table>
如果出于某种原因想订阅模板,那么不要忘记取消订阅,例如:
const listSubcription = this.getList().subscribe((data) => {
this.listItems = data;});
ngOnDestroy() {
listSubcription.unsubscribe();
}
【讨论】:
// Here is sample code
// Componet Name: list.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { NgZone} from '@angular/core';
import {HttpServiceService} from './../http-service.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
constructor(
private http: HttpServiceService,
private zone: NgZone
) { }
brews: object;
ngOnInit(): void {
this.http.getPeople().subscribe(data => {
this.brews = data;
alert(JSON.stringify(this.brews)); // Diplay
console.log(this.brews);
});
}
}
// Here is my http service
// Componet Name: list.component.ts
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class HttpServiceService {
constructor() { }
getPeople(): Observable<any>{
const peopleArray = [{
firstName: 'Al',
lastName: 'Moje',
age: 63
}];
return of(peopleArray);
}
}
【讨论】: