How to access declared internal declaration in AngularJS

I'm new to AngularJS, I need to access the variable that 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); 

variable data1 can be obtained from HTML, but it shows undefined in Javascript

+5
source share
2 answers

Promises are asynchronous. The problem is that when you get to console.log , the $promise.then code is not already running . You must wait for the promise to be fulfilled before you can access this data.

Any operation you want to apply to a value must be performed internally , this callback function that you pass is 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 can update your HTML when it receives data, because $promise is Angular -aware - it knows that after your callback starts, it should tell AngularJS to refresh / redraw your page (and thus refreshing the data) .

+6
source

Since you do not know when the promise returned, therefore it will not be immediately available to you in console.log(this.data1);

You can access your data inside a callback .

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

Source: https://habr.com/ru/post/1247735/


All Articles