gpt4 book ai didi

javascript - 如何将 Promise 的结果传递给 AngularJS 中的 Controller

转载 作者:行者123 更新时间:2023-12-03 09:05:17 26 4
gpt4 key购买 nike

在 Controller 中,我需要检索段的状态。这些段是使用 $resource 从 API 加载的。

在资源中,segmentsresource.js 我有:

angular.module('appApp')
.factory('SegmentsResource', function ($resource) {
return $resource('http://localhost:3000/api/v1/segments/:id');
});

在服务中,segmentsservice.js我有:

angular.module('appApp')
.service('SegmentsService', function (SegmentsResource) {
this.getSegmentStatus = function(segmentId) {
return SegmentsResource.get({
id: segmentId
}, function(segment) {
return segment.status;
})
};
});

我正在尝试返回segment.status,以便我可以在 Controller main.js中使用结果(“可用”、“已翻译”等) >:

$scope.checkAndEditSegment = function(segmentId) {
SegmentsService.getSegmentStatus(segmentId)
.then(function(status) {
if (status === 'available') {
console.log('segment is available');
}
});
};

但是,这不起作用。控制台吐出:TypeError:无法读取未定义的属性“then”,所以我对 promise 有疑问。

如何解决这个问题?

最佳答案

但是当您可以简单地从 Controller 调用工厂时,为什么要走这么长的路线。

angular.module('appApp')
.factory('SegmentsResource', function ($resource) {
return $resource('http://localhost:3000/api/v1/segments/:id');
});

$scope.checkAndEditSegment = function(segmentId) {
SegmentsResource.get(segmentId)
.then(function(status) {
if (status === 'available') {
console.log('segment is available');
}
});
};

关于javascript - 如何将 Promise 的结果传递给 AngularJS 中的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32205466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com