我正在尝试使用 Pinterest JavaScript SDK 获取项目的一些 pin 数据。我在我创建的 Pinterest 服务中有一个方法,该方法在我的 HomeController 中被调用。我尝试将响应放入一个 promise 中,这样我就可以将它放在我的 HomeController 的 $scope
上并在我的 View 中显示它。但是, $scope.pins 在我看来是未定义的。为什么它是 undefined
?似乎 promise 正在奏效。仍在学习 promise 。
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();
});
});
}
家庭 Controller
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 promise 转换为 AngularJS promise:
$q.when(Pinterest.getBoardPins('490329546869188172'))
.then(function (response) {
$scope.pins = response.data;
});
AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 分为经典和 AngularJS 执行上下文。 只有在 AngularJS 执行上下文中应用的操作才能从 AngularJS 数据绑定(bind)、异常处理、属性监视等中受益。
要将 ES6 promise 引入 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.
或者使用 $q constructor. 创建 promise
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 框架及其摘要循环集成的 promise 。
关于javascript - 无法获得在 AngularJS View 中显示的 ES6 promise 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154502/