如何在 AngularJS 中访问在 promise 中声明的变量

How to access variable declared inside promise in AngularJS

我是 AngularJS 的新手,我需要访问在 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);

可以从 HTML 访问变量 data1 但它在 Javascript

中显示 undefined

承诺是异步的。问题是,当您到达 console.log 时, $promise.then 代码还没有 运行 。 您必须等待承诺 fulfilled 才能访问该数据。

您想要应用于该值的任何操作都必须在您传递给 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 能够在获取数据时更新你的 HTML,因为 $promise 是 Angular 感知的——它知道,一旦你的回调有运行,它必须告诉 AngularJS 到 refresh/repaint 你的页面(从而更新数据)。

因为您不知道 promise returns 的时间,所以不会在 console.log(this.data1);

中立即为您提供

您可以在 callback 中访问您的数据。

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