Below are my 2 services. When routing to a url, I resolve "OtherService.promise". But for some routes, I do not want to use the promise, instead I want to use some scope variable in AppService method. How can I achieve this?
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;
}
})
Promises are there for you to use, to avoid nasty callback hell. What it seems you are trying to do is turn an asynchronous process into a synchronous process, which is somewhere that you do not want to go.
Embrace promises, they are EXTREMELY helpful readable, I suggest taking a look at the documentation .
Edit : added a method in the service and a variable in its scope. In the controller you can do AppService.setScope($scope)
and you're good to go.
Not sure I understand what you mean, but would something like this work:
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;
}
})
Should probably add a check to see data is valid when you get
, just to be safe.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.