我已經開發管理應用程序與AngularJS和JAVA作爲服務器端問題的REST API,我現在想的是,如果用戶帶了錯誤的登錄/密碼的情侶,我要處理的錯誤,顯示在客戶端頁面的消息,這裏是我的代碼:AngularJS抓登錄異常
@RequestScoped
@Path("auth")
public class LoginResource {
@Inject
private UserServiceLocal userServiceLocal;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response authenticate(Credentials credentials) {
User userLoggedIn = userServiceLocal.authenticate(
credentials.getUsername(), credentials.getPassword());
if (userLoggedIn != null) {
userServiceLocal.setToken(userLoggedIn, TokenUtils.createToken());
return Response.ok(userLoggedIn).build();
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
}
,這是我的客戶端代碼:
function login(username, password) {
var deferred = $q.defer();
$http
.post(auth_uri, {
username: username,
password: password
})
.then(
function(response) {
if(response){
userInfo = {
accessToken: response.data.token
};
$window.sessionStorage["token"] = response.data.token;
$rootScope.token = response.data.token;
deferred.resolve(response);
}
},
function(error) {
deferred.reject(error);
});
return deferred.promise;
};
和這裏的時候,我消費登錄服務:
function LoginController($scope, $state, authenticationSvc){
$scope.submit = function(credentials) {
authenticationSvc
.login(credentials.username, credentials.password)
.then(
function(response) {
$state.go('dashboard.home');
console.log(response.status);
}, function(error) {
console.log('error.status : ' + error.status)
});
}
};
的問題是,當我試圖發出一個錯誤來測試錯誤響應,我已經在瀏覽器的控制檯上顯示的錯誤,但錯誤callbackof
的承諾沒有抓到,請問有什麼不對?
'error'爲null OR'error.status'爲null 因爲[誤差(https://docs.angularjs.org/api/ng/service/$q)通常一個'字符串'litteral。我說過總是不總是也不一定 –
$ http.post已經返回一個承諾,不需要在這裏使用'$ q' – floribon
@SalathielGenèse,但是在API中,如果在登錄方法中有錯誤,我會返回:Response。狀態(Response.Status.UNAUTHORIZED).build() –