AngularJS:HTTP链接承诺$ Q在服务 [英] AngularJS : chaining http promises $q in a service
问题描述
我有问题,当谈到在angularjs $ HTTP承诺。我这样做在我的服务:(该getSomething函数应链中的两个承诺)
i have problems when it comes to $http promises in angularjs. i am doing this in my service: (the getSomething function should chain two promises)
第二个函数使用外部回调函数!
the second function uses a external callback function!
app.service('blubb', function($http, $q) {
var self = this;
this.getSomething = function(uri, data) {
return self.getData(uri).then(function(data2) {
return self.compactData(uri, data2);
});
};
this.getData = function(uri) {
var deferred = $q.defer();
$http.get(uri).success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject();
});
return deferred.promise;
};
this.compactData = function(uri, data) {
var deferred = $q.defer();
/* callback function */
if(!err) {
console.log(compacted);
deferred.resolve(compacted);
} else {
console.log(err);
deferred.reject(err);
}
/* end of function */
return deferred.promise;
};
});
当我使用这项服务在我的控制器它不输出的console.log:
when i use the service in my controller it doesn't output the console.log:
blubb.getSomething(uri, input).then(function(data) {
console.log(data)
});
编辑:
如果我自己在compactData它的工作原理定义回调函数,但我使用jsonld.compact从<一个href=\"https://raw.github.com/digitalbazaar/jsonld.js/master/js/jsonld.js\">https://raw.github.com/digitalbazaar/jsonld.js/master/js/jsonld.js这不行!
jsonld.compact(input, context, function(err, compacted) {
if(!err) {
console.log(compacted);
deferred.resolve(compacted);
} else {
deferred.reject('JSON-LD compacting');
}
});
我得到在jsonld.compact中的console.log输出,但决心不工作,我不知道为什么。
i am getting the console.log output in jsonld.compact but the resolve doesn't work and i don't know why..
它仅适用于$ rootScope $申请(deferred.resolve(压缩的));
it only works with $rootScope.$apply(deferred.resolve(compacted));
推荐答案
我使用链接的承诺是这样的:
I'm using chaining promises like this:
$http.get('urlToGo')
.then(function(result1) {
console.log(result1.data);
return $http.get('urlToGo');
}).then(function(result2) {
console.log(result2.data);
return $http.get('urlToGo');
}).then(function(result3) {
console.log(result3.data);
});
这篇关于AngularJS:HTTP链接承诺$ Q在服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!