2016-04-26 7 views
1

、私は、ユーザーテープ間違ったログイン/パスワードのカップルならば、私はエラーを処理することを今したいと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であるか 'error.status'は ため[エラー](https://docs.angularjs.org/api/ng/service/$q)nullであります'litteral。レスポンス:私はすでに約束を返し –

+0

$ http.post、必要は '$のq'ここ – floribon

+0

SalathielGenè[email protected]を使用しないように、しかし、ログイン方法に誤りがある場合、APIで、私は返さなければならず、多くの場合、常にではないと述べました。 status(Response.Status.UNAUTHORIZED).build() –

答えて

0

あなたは$のHTTPコールバックでreturn文を忘れてしまいました。または、コメントで示唆されているように、単純化するために$ httpの結果を返すことができます(これはすでに約束です)。

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

は、最後にdeferred.promiseを返すには不十分ですか? –

+0

それはありません。内部のコールバックは、その結果とともに約束を返す必要があります。最終的な約束はあなたのログインコントローラに 'then'メソッドを呼び出すことができるようにあなたに延期された約束を返すだけです。 – Franck

+0

私のコードをどうやって変更すればいいですか? '返す$ http.post(auth_uri、{ ユーザ名:ユーザ名、パスワード :パスワード }) .then( 機能(応答){ のUserInfo = { accessToken:応答 –