我正在使用一个使用RESTful API的角度应用。我正在以这种方式处理用户的身份验证:
// in services.js
app.factory('authService', ['$http', '$q', 'localStorageService',
function ($http, $q, localStorageService) {
var login = function (loginData) {
var data = "grant_type=something&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
$http.post(serviceBase + 'token', data).
success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token });
localStorageService.set('personaData', { username: response.username });
deferred.resolve(response);
}).
error(function(err, status) {
deferred.reject(err);
});
return deferred.promise;
};
和控制器
// controller.js
app.controller('LoginCtrl', ['$scope', '$state', 'authService',
function ($scope, $state, authService) {
$scope.loginData = {
userName: '',
password: ''
};
$scope.alert = {type: '',msg: ''};
$scope.login = function () {
authService.login($scope.loginData).
then(function (response) {
$state.go('index'); // when the service verify that the auth data is correct, the controller redirects to the principal state
}, function (err) {
$scope.alert = {
type: 'danger',
msg: 'non'
};
});
};
}
]);
问题是当用户发送正确的身份验证信息(意思是用户名和密码)时,当响应为200 OK时,服务不会通过.success
回调。是的,仅当响应不是200 OK时才会出现此行为。
资源的确切响应是:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 851
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
Date: Wed, 11 Mar 2015 16:20:12 GMT
{"access_token":"...","token_type":"...","expires_in":"...","username":"...","role":"...","display_name":"..."}
这里发生了什么?我怎么解决这个问题?感谢。
答案 0 :(得分:1)
您不需要创建新的承诺,您只需从$ http调用中返回承诺 - 我认为您调用localStorageService时会发生异常,但它会丢失并且您的承诺永远不会解决。您可以将authService更改为以下内容,并希望您在localStorageService中看到错误:
app.factory('authService', ['$http', '$q', 'localStorageService',
function ($http, $q, localStorageService) {
var login = function (loginData) {
var data = "grant_type=something&username=" + loginData.userName + "&password=" + loginData.password;
return $http.post(serviceBase + 'token', data).
success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token });
localStorageService.set('personaData', { username: response.username });
return response;
});
};