saran sanjeevi
saran sanjeevi

Reputation: 59

Cannot set property 'data' of undefined while access rest API in angular js

I am having error as

TypeError: Cannot set property 'data' of undefined

I try fetch the data from rest api in angularjs using Http get method, Here the code

 getData(){
    this.http({method: 'GET',url:URL})
   .then(function(response) {
       console.log(response.data.id);
       this.data=response.data;// these line shows the error(TypeError: Cannot set property 'setdata' of undefined)
  });  

}

Here console.log(response.data.id); print the id as 123456789 and console.log(response.data); print the entire JSON data.

But While assign the response.datato this.data shows error. But assign the response.datato var data doesn't show error.

Please help me to store the response.data in this.data

Upvotes: 0

Views: 432

Answers (1)

DobleL
DobleL

Reputation: 3928

The problem is that in the line this.data = response.data this is referencing the then callback and not your angular's scope. So the error TypeError: Cannot set property 'data' of undefined is for the data property you are trying to access within this.

Try to save your scope somehow and then use it within the callback.

An example is the famous var vm = this; and then in the callback do vm.data = response.data

Upvotes: 1

Related Questions