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
var a = this; one(). then(function () { console. log(a) }); Update: use an arrow function - they borrow the context ( this ) from their outer scope.
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.
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.
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.
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).
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With