无法在 AngularJS 视图中显示 ES6 承诺值

Can't get ES6 promise value to display in AngularJS view

我正在尝试使用 Pinterest JavaScript SDK 获取项目的一些 pin 数据。我在我创建的 Pinterest 服务中有一个方法,该方法在我的 HomeController 中被调用。我尝试将响应放入一个 promise 中,这样我就可以将它放在我的 HomeController 的 $scope 上并在我的视图中显示它。但是, $scope.pins 在我看来是未定义的。为什么是undefined?似乎诺言正在奏效。还在学习承诺。

Pinterest 服务

function getBoardPins (id) {
  return new Promise(function (resolve, reject) {
    PDK.request('/v1/boards/' + id + '/pins/', 'GET', {fields: 'id,link,url,creator,board,created_at,note,color,counts,media,attribution,image,metadata'}, function (response) {
      if (response) {
        resolve(response);
      }

      reject();
    });
  });
}

家庭控制器

Pinterest.getBoardPins('490329546869188172').then(function (response) {
  $scope.pins = response.data;
});

查看

<h1>Pinterest</h1>
<div ng-repeat="pin in pins">
  <div>{{pin}}</div>
</div>

使用 $q.when 将 ES6 承诺转换为 AngularJS 承诺:

$q.when(Pinterest.getBoardPins('490329546869188172'))
  .then(function (response) {
    $scope.pins = response.data;
});

AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 分为经典和 AngularJS 执行上下文。 只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、 异常处理、属性 监视等

要将 ES6 承诺引入 AngularJS 执行上下文,请使用 $q.when

$q.when

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

— AngularJS $q Service API Reference - $q.when


或者使用 $q constructor.

创建承诺
function getBoardPins (id) {
  //return new Promise(function (resolve, reject) {
  return $q(function (resolve, reject) {
    PDK.request('/v1/boards/' + id + '/pins/', 'GET', {fields: 'id,link,url,creator,board,created_at,note,color,counts,media,attribution,image,metadata'}, function (response) {
      if (response) {
        resolve(response);
      }

      reject();
    });
  });
}

这创建了一个与 AngularJS 框架及其摘要循环集成的承诺。