HTTP GET + NgFor

4

我正在尝试从一个Web服务(JSON结果)检索数据,并在Angular 2组件中呈现它,使用*ngFor。这是我的数据:

{
  "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')。如果我在构造函数中用静态值填充数组,我可以看到数组被显示。在调试器中,我可以看到数据已经正确地检索,但是在这一行:

.subscribe((columnRemote: Array<Object>) => { this.columns = columnRemote});

变量this是类型为Subscriber而不是AppComponent。这正常吗?我做错了吗?我正在使用ES5 TypeScript的Angular2 beta6。

编辑 1:这是调试器为res.json()显示的内容

enter image description here


从上面的代码来看,我认为你正在获取一个对象,但是你却像处理数组一样对待它。尝试使用<li *ngFor="#col of obj.Columns">...</li> - Bhushan Gadekar
我将其视为数组,因为我在.map函数中返回了列数组:.map((res) => res.json().Columns); - Christophe Gigax
1
有问题了兄弟..正在处理中。 - Bhushan Gadekar
1
你是否已经在你的 index.html 文件中添加了 angular2-polyfills.js - Poul Kruijt
1
angular2-polyfills.js 包含 zone.js,该文件由 Angular 用于确定何时更新数据。 - Lucacox
显示剩余3条评论
1个回答

1
为了让 Angular 知道何时更新数据,请在您的 index.html 中添加 angular2-polyfills.js,因为这将包含 zone.js。(感谢 @lucacox)
正确添加库的顺序是:

es6-shim.min.js

system-polyfills.js

angular2-polyfills.js

system.src.js

Rx.js

angular2.dev.js

请注意,随着angular2的发展,所需的库可能会发生变化。当您升级到新版本的angular2时,请始终检查quickstart指南。


好的!还有一个问题:为什么需要 system-polyfills.jses6-shim.min.js - Christophe Gigax
1
这些是Internet Explorer的填充程序。IE需要填充程序来运行依赖于ES2015 promises和动态模块加载的应用程序。其中,es6-shim提供ES2015 promises,而system-polyfills则提供动态模块加载。 - Poul Kruijt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接