Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 490
Prabhu Avatar asked Apr 22 '16 15:04

Prabhu


People also ask

How do you access the variable this inside then scope?

var a = this; one(). then(function () { console. log(a) }); Update: use an arrow function - they borrow the context ( this ) from their outer scope.

What is resolve in promise angular?

The Promise.resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

What is AngularJS promise?

Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.

What is promise and then in angular?

Promises can be executed by calling the then() and catch() methods. The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected. The catch() method takes one callback function and is invoked when an error occurs.


2 Answers

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

like image 78
Ven Avatar answered Oct 27 '22 00:10

Ven


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);
});
like image 21
Thalaivar Avatar answered Oct 26 '22 23:10

Thalaivar