Javascript AngularJS从承诺中获取返回值
我有这个服务:Javascript AngularJS从承诺中获取返回值,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,我有这个服务: 'use strict'; app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) { var out = []; if (authService.authentication.isAuth == false) { $location.path('/login');
'use strict';
app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) {
var out = [];
if (authService.authentication.isAuth == false) {
$location.path('/login');
out = "effettuare login";
}
else {
customerService.getCustomerAnagrafica().then(
function (results) {
out = results.data;
}, function (error) {
//alert(error.data.message);
});
}
return { out: out };
}]);
我想返回results.data的值
我想做一些像这样的把戏\u this=this
我试着把那个代码放在后面,然后(
没有成功
我的目标是从该服务中获取results.data
要从控制器调用,只需这样做:
$scope.myResults=loggedService.out;
您可以使用观察者,但这不是最佳方式。您的工厂应返回承诺,并且您的控制器应使用它在$scope中进行交互
每次您的服务必须与scope交互时,您也必须使用承诺。您需要返回承诺..因此您的代码..很抱歉我在浏览器中编写了此内容..因此我可能有一个拼写错误
'use strict';
app.factory('loggedService', ['$q','$http', 'authService', 'customerService', function ($q,$http, authService, customerService) {
var deferred = $q.defer();
if (authService.authentication.isAuth == false) {
$location.path('/login');
deferred.resolve("effettuare login");
}
else {
customerService.getCustomerAnagrafica().then(
function (results) {
deferred.resolve(results.data)
}, function (error) {
//alert(error.data.message);
});
}
return deferred;
}]);
您可以调用loggedService。promise。然后(函数(数据){..您通过不使用promise而使用闭包来创建竞争条件。换句话说,当您将闭包用于其他事情时,您的异步作业可能尚未填充闭包 这基本上就是你正在做的:
var闭包='尚未';
var getReady=function(){
var func=函数(){
结束语='我准备好了';
}
设置超时(func,1000);
};
getReady();
警报(关闭);
//尚未准备就绪(因为需要1000毫秒)。
您应该从服务返回承诺,并填充服务的结果。返回的内容;{out:undefined}
。?如果out未定义,则表示results.data未定义,否则它将是一个空数组。results.data已填充,问题是out-in-out=results.data;与var-out=[]不同……事实上,我的输出是[]loggedService。然后(函数(数据){$scope.pp=data;});它告诉我loggedService不支持。那么Method不需要为此使用另一个承诺。customerService.GetCustomerAgraFica().then();
应该返回一个承诺(如果它遵循承诺a+,那么它应该作为一个可启用对象返回)。所以您需要返回它。然后loggedService.Then应该可以工作。但是,resolve函数应该返回results.data
,而不是deferred.resolve(results.data);
从控制器运行这个:loggedService.Then(function(data){u this.pp=data;});但是当我运行控制台时,返回的是then方法不是loggedServiceI方法,我认为当我采用上述解决方案时,我理解我犯了这个错误。