5

I am new to the AngularJS, I need to access the variable which is assigned inside the promise in Javascript

this.reqData= this.profileService.getData();
var resp1 = angular.fromJson(this.reqData);
this.data1;

var that = this;
resp1.$promise.then(function (data) {
  that.data1= data.resource.resource;
}).catch(function (error) {
  console.log(error);
});

console.log(this.data1);

the variable data1 can be accessed from HTML but it is showing undefined in Javascript

1
  • You don't access it outside of the promise. You cannot fetch the value from the future (unless you invent time travel). Commented Apr 22, 2016 at 15:10

2 Answers 2

6

Promises are asynchronous. The problem is that, when you get to the console.log, the $promise.then code didn't run yet. You have to wait for the promise to be fulfilled before you can access that data.

Any operation you want to apply to the value must be done inside that callback function you're passing to then:

resp1.$promise.then(function (data) {
  var data1 = data.resource.resource;
  // do all your processing on data1 *here*
  console.log(data1);
}).catch(function (error) {
  console.log(error);
});

AngularJS is able to update your HTML when it gets the data, because $promise is Angular-aware – it knows that, once your callback has run, it has to tell AngularJS to refresh/repaint your page (and thus update the data).

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

Comments

1

Because you don't know when the promise returns, so it won't be immediately available for you in console.log(this.data1);

You can access your data inside the callback.

resp1.$promise.then(function (data) {
  that.data1= data.resource.resource;
  }).catch(function (error) {
  console.log(error);
});

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.