2016-04-26 83 views
1

我已經開發管理應用程序與AngularJSJAVA作爲服務器端問題的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的承諾沒有抓到,請問有什麼不對?

+0

'error'爲null OR'error.status'爲null 因爲[誤差(https://docs.angularjs.org/api/ng/service/$q)通常一個'字符串'litteral。我說過總是不總是也不一定 –

+0

$ http.post已經返回一個承諾,不需要在這裏使用'$ q' – floribon

+0

@SalathielGenèse,但是在API中,如果在登錄方法中有錯誤,我會返回:Response。狀態(Response.Status.UNAUTHORIZED).build() –

回答

0

您忘記了$ http回調中的return語句。或者如評論中所建議的,您可以返回$ http的結果來簡化(這已經是一個承諾)。

...function(error) { return deferred.reject(error);}); 
+0

不足以最終返回deferred.promise? –

+0

不,它不是。內部回調需要返回承諾和結果。最後的承諾只是返回延期的承諾,讓你能夠在你的登錄控制器中調用'then'方法。 – Franck

+0

我該如何修改我的代碼? –