我在 Angular 中获得了一项服务:
App.factory('AuthService', function ($q, $http, CredentialStorage) {
var _endpoint = 'http://localhost:3000';
return {
login: function (credentials) {
return $http
.post('/api/users/login', credentials)
.success(function (apiResult) {
var deferred = $q.defer();
if (apiResult.code == 0) {
$scope.user = apiResult.context;
CredentialStorage.store(apiResult.context);
}
return deferred.promise;
})
.fail(function(apiResult, status, headers) {
var deferred = $q.defer();
return deferred.promise;
});
},
....});
我对用户进行身份验证并将其存储在某些 cookie 或其他内容中(这不相关)。
然后在我的 Controller 上我得到:
App.controller('LoginController', function ($scope, $rootScope, AuthService) {
var _login = function($event) {
$event.preventDefault();
AuthService.login($scope.l).then(function() {
alert('aaa');
if (!AuthService.authenticatedUser) {
$scope.errors = ['Invalid username and password. Please try again.'];
alert($scope.errors);
} else {
alert('a' + $scope.errors);
}
})
}
$scope.login = _login;
});
出于某种原因,我的 Controller 无法执行。这是为什么?
谢谢
最佳答案
嗯,简单的答案是:您使用链式的 .then
而不是仅添加监听器的 success
:
App.factory('AuthService', function ($q, $http, CredentialStorage) {
var _endpoint = 'http://localhost:3000';
return {
login: function (credentials) {
return $http
.post('/api/users/login', credentials)
.then(function (response) {
var apiResult = response.data;
if (apiResult.code == 0) {
CredentialStorage.store(apiResult.context);
return apiResult.context; // promises let you return the value
}
throw new Error("Authentication failed"); // return $q.reject
// if you don't want to invoke
// exceptionHandler
});
},
....});
这会让你这样做:
AuthService.login($scope.l).then(function(result) {
$scope.user = result;
}).catch(function(err){
// code to handle the case authorization failed or the API call failed
});
从 Angular 关注点分离的 Angular 来看,修改服务/工厂/提供者中的 UI 范围通常是不好的。最好返回结果。
关于javascript - Angular promise ( promise ?)。或者我如何在 Angular $http.success 之后链接 .then,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23713779/