Vaibhav Sharma
Vaibhav Sharma

Reputation: 113

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.

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);

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)

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.

Upvotes: 3

Views: 495

Answers (1)

eko
eko

Reputation: 40647

As @JBNizet mentioned the problem in the comment section, you are logging a value which you are expecting asynchronously.

Your getSingleKey() method is an async method, meaning you can't guess when the response will arrive (network speed etc.).

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

Upvotes: 1

Related Questions