Reputation: 10703
I think I need (but I'm not sure) to use a promise in my Angularjs app. This following code is within my controller and it calls a .service
(not a .factory
if that's relevant?) called processString
.
//complete this first
var item = MagicBoxService.processString(str);
//and then do this
$scope.task.items.push({ content_type: item.content_type, provider: item.provider, front: item.front, data: item.data });
$scope.save = true;
The service needs to communicate with a 3rd party API (as well as my own) to get the data. This happens very quickly but the item
variable is empty when the next part of the code is executed.
I've tried a $timeout
on the API call but this doesn't seem to work so I thought maybe a promise is what I need to use so I've tried the following:
var item = MagicBoxService.processString(str).then(function() {
$scope.task.items.push({ content_type: item.content_type, provider: item.provider, front: item.front, data: item.data });
$scope.save = true;
})
but this gives me undefined is not a function. Any advice/code would be much appreciated.
EDIT
Here is an edited version of my .service
.
this.processString = function(str) {
...
oEmbedService.query({url: str}, function(response) {
item.content_type = "image";
item.provider = "Flickr";
item.data = response.content.url;
item.front = $sce.trustAsResourceUrl(item.data);
})
...
return item
};
Upvotes: 2
Views: 151
Reputation: 18523
if your processString()
function looks like this:
function(str) {
var promiseManager = $q.defer();
...
oEmbedService.query({url: str}, function(response) {
var item = {};
item.content_type = "image";
item.provider = "Flickr";
item.data = response.content.url;
item.front = $sce.trustAsResourceUrl(item.data);
promiseManager.resolve(item);
})
...
return promiseManager.promise;
};
Then you can call it like this:
MagicBoxService.processString(str).then(function(item) {
$scope.task.items.push({ content_type: item.content_type, provider: item.provider, front: item.front, data: item.data });
$scope.save = true;
})
Upvotes: 4