如何在typeScript

时间:2019-03-06 10:29:55

标签: json typescript angular7

如何访问打字稿中的JSON属性?

我正在制作Angular Project。

    test:string;
    response:any;

    web_assign() {
    this.http.get(this.url1).subscribe( e => this.response = e);
    this.test = "OK";
    this.t=this.response.name2;
    return false;}

在此行显示错误。 this.t=this.response.name2; 它说它无法读取'name2'的属性

1 个答案:

答案 0 :(得分:1)

您需要在订阅回调中进行分配:

this.http.get(this.url1)
    .subscribe( e => {
        this.response = e;
        this.test = "OK";
        this.t=this.response.name2;
    });

http.get是异步的,this.response仍不会在下一行中定义,但是它将在subscribe回调中定义。