Reputation: 129
In a controller, I need to retrieve the status of a segment. The segments are loaded from an API using $resource
.
In the resource, segmentsresource.js
I have:
angular.module('appApp')
.factory('SegmentsResource', function ($resource) {
return $resource('http://localhost:3000/api/v1/segments/:id');
});
In the service, segmentsservice.js
I have:
angular.module('appApp')
.service('SegmentsService', function (SegmentsResource) {
this.getSegmentStatus = function(segmentId) {
return SegmentsResource.get({
id: segmentId
}, function(segment) {
return segment.status;
})
};
});
I'm trying to do return segment.status
so I can use the result ('available', 'translated', etc) in the controller, main.js
:
$scope.checkAndEditSegment = function(segmentId) {
SegmentsService.getSegmentStatus(segmentId)
.then(function(status) {
if (status === 'available') {
console.log('segment is available');
}
});
};
However, this doesn't work. Console spits: TypeError: Cannot read property 'then' of undefined'
, so I have a problem with promises.
How to fix this?
Upvotes: 0
Views: 418
Reputation: 129
I resolved using $q
:
In the service:
this.getSegmentStatus = function(segmentId) {
var dfd = $q.defer();
SegmentsResource.get({ id: segmentId }, function(segment) {
dfd.resolve(segment.status);
})
return dfd.promise;
};
In the controller:
SegmentsService.getSegmentStatus(segmentId)
.then(function(status) {
console.log(status);
});
Upvotes: 0
Reputation: 2300
But why you are taking this long route when you can simply call the factory from 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');
}
});
};
Upvotes: 1