以下是我的2项服务。当路由到网址时,我解决" OtherService.promise"。但是对于某些路由,我不想使用promise,而是想在AppService方法中使用一些范围变量。我怎样才能做到这一点?
app.factory("AppService", function(OtherService){
var object = {};
object.method = function() {
return OtherService.get();
}
return object;
});
app.factory("OtherService", function($http) {
var data = null;
var promise = $http.get('/get').success(function (response) {
data = response
});
return {
promise: promise,
get: function(){
return data.html;
}
})
答案 0 :(得分:0)
承诺是供您使用,以避免令人讨厌的回调地狱。你似乎要做的是将异步进程转变为同步进程,这是你不想去的地方。
接受承诺,它们非常有用,我建议您查看documentation。
答案 1 :(得分:0)
编辑:在服务中添加了一个方法,在其范围内添加了一个变量。在控制器中,您可以执行AppService.setScope($scope)
,然后您就可以了。
我不确定我理解你的意思,但是这样的工作会有所作为:
app.factory("AppService", function(OtherService){
var scope = {};
var object = {};
object.method = function(mode) {
return mode === 'promise' ? OtherService.get() : scope;
}
object.setScope = function(_scope) {
scope = _scope;
}
return object;
});
app.factory("OtherService", function($http) {
var data = null;
var promise = $http.get('/get').success(function (response) {
data = response
});
return {
promise: promise,
get: function(){
return data.html;
}
})
为了安全起见,您应该在get
添加支票以查看数据是否有效。