【问题标题】:Angular2 http get json issueAngular2 http获取json问题
【发布时间】: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


    【解决方案1】:

    在 CD 启动时的视图中,data.Id 插值尝试评估,但尚未定义 data 对象。所以当它试图从中访问Id 属性时,它会抛出一个错误。

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

    我想指出的另一件事是,再次使用 wall 元素没有任何意义,因为您已经在渲染 wall 组件。(我知道它不会起作用,因为我们还没有提供它在directives 的Component 选项内)

    【讨论】:

    • 似乎错误消失了,但没有显示数据
    • @DasBoot 你得到正确的data 打印在控制台吗?
    • 是的,但正如我提到的 console.log(this.data);返回 undefined while console.log(json);工作正常并正确返回数据。
    • @DasBoot 这是正确的事情。异步调用将在完成后返回一个数据。这里subscribe 充当回调函数,在ajax 完成后调用。你能粘贴一个data 在这里,我认为您正在获取数组格式的数据.. 还是它的对象?
    • 看起来它正在工作。似乎是?标志已经修好了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-10-11
    • 2016-11-28
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多