0

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

3
  • please post more relevant code, also initialization of this.data Commented May 23, 2018 at 11:31
  • Why you are using this you can use $scope.data. Commented May 23, 2018 at 11:32
  • (function(response) { ... }).bind(this) Commented May 23, 2018 at 11:32

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.