[英]How to pass the result of a promise to a controller in AngularJS
在控制器中,我需要檢索段的狀態。 使用$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;
})
};
});
我正在嘗試return segment.status
以便可以在控制器main.js
使用結果(“ available”,“ translated”等):
$scope.checkAndEditSegment = function(segmentId) {
SegmentsService.getSegmentStatus(segmentId)
.then(function(status) {
if (status === 'available') {
console.log('segment is available');
}
});
};
但是,這不起作用。 控制台吐痰: TypeError: Cannot read property 'then' of undefined'
,所以我對promises有問題。
如何解決這個問題?
但是為什么只需要從控制器致電工廠就選擇了這條漫長的路。
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');
}
});
};
我用$q
解決$q
:
在服務中:
this.getSegmentStatus = function(segmentId) {
var dfd = $q.defer();
SegmentsResource.get({ id: segmentId }, function(segment) {
dfd.resolve(segment.status);
})
return dfd.promise;
};
在控制器中:
SegmentsService.getSegmentStatus(segmentId)
.then(function(status) {
console.log(status);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.