How to access variable declared inside promise in AngularJS
Asked Answered
P

2

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

Patroclus answered 22/4, 2016 at 15:4 Comment(1)
You don't access it outside of the promise. You cannot fetch the value from the future (unless you invent time travel).Polito
F
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).

Firstling answered 22/4, 2016 at 15:9 Comment(0)
S
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);
});
Subpoena answered 22/4, 2016 at 15:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.