我正在尝试从Web服务(
JSON结果)中检索数据,并使用* ngFor在Angular 2组件中呈现它.这是我的数据:
{ "Columns": [ {"Label": "CodeProduct"},{"Label": "productfamily_ID"},{"Label": "description"} ] }
这是我的Angular组件:
import {Component,View} from 'angular2/core'; import {Http,Response} from 'angular2/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app',templateUrl: './app/app.html' }) export class AppComponent { columns: Array<Object> = []; constructor(private http: Http){} ngOnInit() { this.getProducts() .subscribe( (columnRemote: Array<Object>) => { this.columns = columnRemote}); }; private _url = 'api/data/product'; getProducts() { return this.http.get(this._url) .map((res) => res.json().Columns); } }
我的模板:
<h3>Hello StackOverFlow</h3> <ul> <li *ngFor="#column of columns">{{column.Label}}</li> </ul>
我可以看到标题出现,但不是我的列列表(即使我尝试使用静态字符串,例如< li>中的’Test’).如果我在构造函数中使用静态值填充我的数组,我可以看到显示的数组.
在debuger中我可以看到数据被正确检索,但在这一行:
.subscribe((columnRemote: Array<Object>) => { this.columns = columnRemote});
变量属于Subscriber类型,而不是AppComponent类型.这是正常的吗?我做错了吗?我正在使用ES5 TypeScript的Angular2 beta6.
编辑1:这是debuger告诉我res.json()
解决方法
为了能让角知道何时更新数据,将angular2-polyfills.js添加到index.html,因为这将包括zone.js
(感谢@lucacox)
添加库的正确顺序是:
ES6-shim.min.js
系统polyfills.js
angular2-polyfills.js
system.src.js
Rx.js
angular2.dev.js
请注意,随着angular2的成熟,必要的库可能会随着时间的推移而发生变化.当您更新到更新版本的angular2时,请务必查看quickstart指南.