Angular2 http获取json问题

时间:2016-04-07 19:08:47

标签: json typescript angular

尝试在angular2视图中显示http json响应。为了让我开始,我已经完成了针对.NET核心的特定教程和使用Typescript的Angular2。一切都很好,所以我尝试修改它,但看起来我卡住了,找不到答案。这是我到目前为止所做的。

wall.main.component.ts

import {Component, OnInit} from "angular2/core";
import {CORE_DIRECTIVES} from "angular2/src/common/directives/core_directives";
import {WallService} from "./wall.service";

@Component({
    selector: "wall",
    templateUrl: "app/components/wall/wall.main.html",
    providers: [WallService],
    directives: CORE_DIRECTIVES
})
export class WallComponent implements OnInit {
    data: any;

    constructor(private service: WallService) { }

    ngOnInit() {
        this.get();
        console.log(this.data);
    }

    get() {
        this.service.get().subscribe((json: any) => {
            console.log(json);
            this.data = json;
        });
    }
}

wall.service.ts

import "rxjs/Rx"
import {Http} from "angular2/http";
import {Injectable} from "angular2/core";

@Injectable()
export class WallService {
    constructor(private http: Http) { }

    get() {
        return this.http.get("wall/getwallposts").map(response => response.json());
    }
}

wall.main.html

<wall>
    <p>{{data.Id}}</p>
    <p>{{data.Body}}</p>
</wall>

Html不显示数据。错误:

TypeError: Cannot read property 'Id' of undefined in [{{data.Id}} in WallComponent@3:7]

尝试了很多方法。使用索引数据[0]访问数组.Id,更改变量类型,什么都没有。此console.log(json)工作正常。我可以在控制台中看到和读取对象,但另一个console.log(this.data)显示未定义,我希望它是相同的。我错过了什么?

1 个答案:

答案 0 :(得分:4)

在CD启动时查看,data.Id插值会尝试评估,但data对象尚未定义。因此,当它尝试从中访问Id属性时,会抛出错误。

<wall>
    <p>{{data?.Id}}</p>
    <p>{{data?.Body}}</p>
</wall>

我想指出的另一件事是,再次拥有wall元素是没有意义的,因为你已经渲染了一个wall组件。(我知道它不会起作用,因为我们尚未在directives

Component选项中提供