Angular2模板好像等待列表从这样的observable返回:
<li *ngFor="let product of products">
{{product.DisplayProductName}}
</li>
...
export class PublicProductListComponent {
errorMessage: string;
products: Products[];
mode = 'Observable';
constructor(private productService: ProductService) { }
ngOnInit() { this.getPublicProducts(); }
getPublicProducts() {
this.productService.getPublic()
.subscribe(
products => this.products = products,
error => this.errorMessage = <any>error);
}
}
但是当我尝试用对象(userDash
)做同样的事情时,我得到的错误是该对象未定义,因为它没有等待订阅查找数据:
<li *ngFor="let prod of userDash.OwnedProducts">
{{prod.DisplayProductName}}
</li>
...
export class OwnedProductListComponent {
errorMessage: string;
userDash: UserDashboard;
mode = 'Observable';
constructor(private userService: UserService) { }
ngOnInit() { this.getUserDashboard(); }
getUserDashboard() {
this.userService.getUserDashboard()
.subscribe(
dashboard => this.userDash = dashboard,
error => this.errorMessage = <any>error);
}
}
执行null / undefined检查似乎有效,但我无法弄清楚它是否是最有角度的方法。
<ul *ngIf="userDash">
<li *ngFor="let dash of userDash.OwnedProducts">
{{dash.DisplayProductName}}
</li>
</ul>
我仍然想尝试学习这种模式,所以请原谅我的无知。
编辑---这是getUserDashboard()
getUserDashboard(): Observable<UserDashboard> {
return this.http.get(siteSettings.apiURL + "user/" + this.authService.getClientID() + "/dashboard", this.authService.getAuthorizationHeaders())
.map(function (res: Response) {
let body = res.json();
return body;
})
.catch(this.handleError);
}
答案 0 :(得分:2)
尝试在构造函数中创建对象。
在OwnedProductListComponent.ts
中constructor(private userService: UserService) {
this.userDash = new UserDashboard();
}
在UserDashboard Model类中
export class UserDashboard{
constructor() {
this.OwnedProducts = new Products()
}
}
答案 1 :(得分:1)
在任何一种情况下,我都不认为棱角等待观察者。我认为* ngFor只支持循环未定义,而在第二种情况下,解析userDash.OwnedProducts会在开始循环之前抛出JS错误。
这也有效:
<li *ngFor="let product of undefined">{{product}}</li>
检查这个plunker:
http://plnkr.co/edit/hvvJcz5IHCYscF3N3XtC?p=preview
[编辑]
要解决您的问题,请使用@rook建议的异步管道(您必须使用* ngFor而不是Observable<Array<T>>
而不是Array<T>
)。
详细示例如下: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
或只是初始化您的数据。