2013-09-24 11 views
8

Utilizzando $ http posso rilevare gli errori come 401 facilmente:Come rilevare un 401 (o un altro errore di stato) in una chiamata di servizio angolare?

$http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'}). 
success(function(data, status, headers, config) { 
    $scope.posts = data; 
}). 
error(function(data, status, headers, config) { 
    if(status == 401) 
    { 
     alert('not auth.'); 
    } 
    $scope.posts = {}; 
}); 

Ma come posso fare qualcosa di simile quando si utilizzano i servizi, invece. Ecco come appare il mio attuale servizio:

myModule.factory('Post', function($resource){ 
    return $resource('http://localhost/Blog/posts/index.json', {}, { 
      index: {method:'GET', params:{}, isArray:true} 
    }); 
}); 

(Sì, sto solo imparando angolare).

SOLUZIONE (grazie a Nitish Kumar e tutti i collaboratori)

Nel controllore Messaggio stavo chiamando il servizio come questo:

function PhoneListCtrl($scope, Post) { 
    $scope.posts = Post.query(); 
} 
//PhoneListCtrl.$inject = ['$scope', 'Post']; 

come suggerito dalla risposta selezionata, ora io' m chiamandolo così e funziona:

function PhoneListCtrl($scope, Post) { 
    Post.query({}, 
    //When it works 
    function(data){ 
     $scope.posts = data; 
    }, 
    //When it fails 
    function(error){ 
     alert(error.status); 
    }); 
} 
//PhoneListCtrl.$inject = ['$scope', 'Post']; 

risposta

10

in chiamata controller Post like.

Post.index({}, 
      function success(data) { 
       $scope.posts = data; 
      }, 
     function err(error) { 
      if(error.status == 401) 
      { 
      alert('not auth.'); 
      } 
      $scope.posts = {}; 
     } 
); 
1

Le risorse restituiscono promesse proprio come http. Semplicemente gancio nel risoluzione errore:

Post.get(...).then(function(){ 
    //successful things happen here 
}, function(){ 
    //errorful things happen here 
}); 

AngularJS Failed Resource GET

1

$ http è un servizio, proprio come $ risorsa è un servizio.

myModule.factory('Post', function($resource){ 
    return $http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'}); 
}); 

Questo restituirà la promessa. Puoi anche usare una promessa all'interno della tua fabbrica e fare in modo che la tua fabbrica (servizio) faccia tutto per te.

Problemi correlati