Prabhu
Prabhu

Reputation: 404

How to access variable declared inside promise in AngularJS

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

Upvotes: 5

Views: 1175

Answers (2)

Thalaivar
Thalaivar

Reputation: 23642

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

Upvotes: 1

Ven
Ven

Reputation: 19040

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

Upvotes: 6

Related Questions