简体   繁体   English

如何将AngularJS2响应对象分配给类对象

[英]how to assign AngularJS2 response object to class object

I am working on a project in angularJS2 and using $http with observable to parse the JSON from rest API and here is my code. 我正在使用angularJS2中的一个项目,并使用带有observable的$ http来解析来自rest API的JSON,这是我的代码。

Service: 服务:

getSingleKey(id:any){

    var headers = new Headers();
    headers.append('content-Type','application/json');

    return this.http.get(
        'http://192.168.1.59/keyapp/api/getKeyspiration/'+id+'.json'
        ).map(res => res.json());       

} }

Component: 零件:

private dataKey: Object = {};

this.keyService.getSingleKey(this.id)
      .subscribe( 

        data=> 
      {
          console.log(data.data),
          this.dataKey=data.data
      },
      error=>console.log(error)
      );

console.log(this.dataKey); 的console.log(this.dataKey);

and i am getting the following response: 我收到以下回复:

GET 
localhost/keyapp/api/getKeyspiration/15.json [HTTP/1.1 200 OK 398ms]

// response for console.log(data.data) //对console.log的响应(data.data)

Object { k_id: 15, k_u_id: 5, k_type: 3, k_title: "vaibhav", k_text: "", k_data: "2024067187.png", k_thumb: "", k_added_date: "2016-11-24T06:10:23+0000" }

// response for  console.log(this.dataKey)

Object {  }

In short, I am getting the response data but how can i assign the response object to my class object, Am i missing something in my code. 简而言之,我正在获取响应数据但是如何将响应对象分配给我的类对象,我在代码中遗漏了一些东西。 thanks in advance for your help. 在此先感谢您的帮助。

As @JBNizet mentioned the problem in the comment section, you are logging a value which you are expecting asynchronously. 由于@JBNizet在注释部分中提到了问题,因此您正在记录一个异步期望的值。

Your getSingleKey() method is an async method, meaning you can't guess when the response will arrive (network speed etc.). 你的getSingleKey()方法是一个异步方法,这意味着你无法猜测响应何时到达(网络速度等)。

You must do whatever you plan to do with the response, inside the callback of the async function: 在异步函数的回调中,您必须执行您计划对响应做的任何事情:

private dataKey: Object = {};

this.keyService.getSingleKey(this.id)
      .subscribe( 

        data=> 
      {
          console.log(data.data),
          this.dataKey=data.data;
          console.log(this.dataKey); //will be defined since it is in the async functions
          //callback scope, so do whatever you want to do with this.dataKey here
      },
      error=>console.log(error)
      );
console.log(this.dataKey); //will be undefined since it is out of the async functions callback scope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM