加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2 http获取json问题

发布时间:2020-12-17 07:11:35 所属栏目:安全 来源:网络整理
导读:尝试在angular2视图中显示http json响应.为了让我开始,我已经完成了针对.NET核心的特定教程和使用Typescript的Angular2.一切都很好,所以我尝试修改它,但看起来我卡住了,找不到答案.这就是我到目前为止所拥有的. wall.main.component.ts import {Component,On
尝试在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)显示未定义,我希望它是相同的.我错过了什么?

解决方法

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

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

我想指出的另一件事是,没有任何意义可以再次使用wall元素,因为你已经渲染了一个wall组件.(我知道它不会工作,因为我们没有在Component的指令选项中提供它)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读