【发布时间】:2016-07-28 20:39:52
【问题描述】:
尝试在 angular2 视图中显示 http json 响应。为了让我开始,我已经完成了使用 Typescript 的 .NET core 和 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]
尝试了很多方法。使用索引 data[0].Id 作为数组访问,更改变量类型,什么都没有。这个 console.log(json) 也可以正常工作。我可以在控制台中查看和读取该对象,但另一个 console.log(this.data) 显示未定义,我希望它是相同的。我错过了什么?
【问题讨论】:
标签: json typescript angular