我是Angularjs的新手,我正在努力找到做这种流程的最佳结构:
我的工厂目前看起来像这样
app.factory('SomeFactory',['$resource', function($resource){
//access_token only needs to be set once
var access_token = 0;
var request = $resource('/my/server/').get();
request.promise.then(function(result){
access_token = result;
}
);
return $resource('https://third.party/:token',{token: access_token});
}])
我无法设置access_token,回调函数会以某种方式被破坏。
另外我如何形成一个链,以便在首先设置access_token之前不能调用第三方?
答案 0 :(得分:0)
试试这个
app.factory('SomeFactory',['$resource, $q', function($resource, $q){
var service = {};
//access_token only needs to be set once
var access_token = null;
getAccessToken = function() {
var deferred = $q.defer();
if (access_token) {
deferred.resolve(access_token);
} else {
$resource('/my/server/').then(function(result){
access_token = result;
deferred.resolve(access_token);
});
}
return deferred.promise;
}
service.callThirdParty = function() {
var deferred = $q.defer();
getAccessToken.then(function(access_token) {
$resource('https://third.party/:token',{token: access_token}).then(function(result) {
deferred.resolve(result);
})
})
return deferred.promise;
}
return service;
}]);