2014-12-16 10 views
41

Sto leggendo un libro intitolato "Pro Angular JS". Tuttavia, ho una domanda su come rilevare lo stato di errore.

Quello che ho codificato è:

$http.get(dataUrl) 
    .success(function (data){ 
     $scope.data.products = data; 
    }) 
    .error(function (error){ 
     $scope.data.error=error; 
     console.log($scope.data.error.status); // Undefined! 
     // (This is the spot that I don't get it.)           
    }); 

Se il codice I "console.log ($ scope.data.error.status);" , perché l'argomento di console.log non è definito?

Nel libro, c'è una frase, "L'oggetto passato alla funzione di errore definisce proprietà di stato e messaggio."

così ho fatto $ scope.data.error.status

Perché è sbagliato?

+0

Qual è il messaggio se si esegue semplicemente 'console.log ($ scope.data.error);'? – Clawish

+0

@Clawish Quindi, viene stampato "Not Found". Tuttavia, quello che voglio stampare è "404" – nujabes

+0

Grazie per tutti i ragazzi !! Perché c'erano così tante risposte utili anche se è la mia prima domanda in questo sito, sono così felice! E 'davvero un buon sito !! – nujabes

risposta

43

Gli argomenti non sono corretti, l'errore non restituisce un oggetto contenente stato e messaggio, li ha passati come parametri separati nell'ordine descritto di seguito.

tratto dal angular docs:

  • dati - {string | Object} - Il corpo di risposta trasformato con le funzioni di trasformare.
  • stato - {numero} - codice di stato HTTP della risposta.
  • intestazioni - {function ([headerName])} - Funzione getter intestazione.
  • config - {Object} - L'oggetto di configurazione utilizzato per generare la richiesta.
  • statusText - {string} - Testo di stato HTTP della risposta.

Quindi sarebbe necessario modificare il codice per:

$http.get(dataUrl) 
    .success(function (data){ 
     $scope.data.products = data; 
    }) 
    .error(function (error, status){ 
     $scope.data.error = { message: error, status: status}; 
     console.log($scope.data.error.status); 
    }); 

Ovviamente, non c'è bisogno di creare un oggetto che rappresenta l'errore, si può solo creare le proprietà dell'ambito separati ma lo stesso principio si applica.

+0

Grazie mille! Quindi, il libro è sbagliato? Nel libro "L'oggetto passato alla funzione di errore definisce le proprietà di stato e del messaggio". L'angolare è cambiata? – nujabes

+0

Grazie DoctorMick !! ^^ – nujabes

+0

Non riesco a vedere nulla nel registro delle modifiche che indica che questo è cambiato. – DoctorMick

3

Stato risposta viene come secondo parametro nella richiamata, (from docs):

// Simple GET request example : 
$http.get('/someUrl'). 
    success(function(data, status, headers, config) { 
    // this callback will be called asynchronously 
    // when the response is available 
    }). 
    error(function(data, status, headers, config) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
    }); 
+0

Grazie !!! ^^ – nujabes

8

aggiornamento: partire dal angularjs 1.5, promettono metodi di successo e l'errore sono stati deprecati. (Vedi this answer)

da current docs:

$http.get('/someUrl', config).then(successCallback, errorCallback); 
$http.post('/someUrl', data, config).then(successCallback, errorCallback); 

è possibile utilizzare altri argomenti della funzione in questo modo:

error(function(data, status, headers, config) { 
    console.log(data); 
    console.log(status); 
} 

vedere $http docs:

// Simple GET request example : 
$http.get('/someUrl'). 
    success(function(data, status, headers, config) { 
    // this callback will be called asynchronously 
    // when the response is available 
    }). 
    error(function(data, status, headers, config) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
    }); 
+0

Grazie mille! Quindi, il libro è sbagliato? Nel libro "L'oggetto passato alla funzione di errore definisce proprietà di stato e di messaggio". L'angolazione è cambiata? – nujabes

+0

Lo ricordo lo stesso .. assicurati di leggere sempre i documenti, e che sono per la tua versione di angolare. (c'è un menu a discesa con tutte le versioni disponibili) –

+0

Grazie Nitsan !! – nujabes

6

dalla Gazzetta angular documentation

// Simple GET request example : 
$http.get('/someUrl'). 
    success(function(data, status, headers, config) { 
    // this callback will be called asynchronously 
    // when the response is available 
    }). 
    error(function(data, status, headers, config) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
    }); 

Come si può vedere il primo parametro per la richiamata errore è dati uno stato è secondo.

+1

Le persone che leggono questo, da 1.4 angolare, '.success' e' .error' sono state deprecate in favore di '.then' – yorch

+0

E da Angular 1.6,' .success' e '.error' non sono più disponibili, sei costretto a usare '.then' e forse' .catch' – jperelli

6

Dal $http.get restituisce una 'promessa' con i metodi di una maggiore comodità success e error (che ha appena avvolgere il risultato di then) si dovrebbe essere in grado di utilizzare (a prescindere dalla vostra versione angolare):

$http.get('/someUrl') 
    .then(function success(response) { 
     console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText 
    }, function error(response) { 
     console.log('failed', response); // supposed to have: data, status, headers, config, statusText 
    }) 

Non è propriamente una risposta alla domanda, ma se sei stato morso dal problema "La mia versione di Angular è diverso dal documento" puoi sempre scaricare tutto il arguments, anche se non conosci il metodo appropriato firma:

$http.get('/someUrl') 
    .success(function(data, foo, bar) { 
    console.log(arguments); // includes data, status, etc including unlisted ones if present 
    }) 
    .error(function(baz, foo, bar, idontknow) { 
    console.log(arguments); // includes data, status, etc including unlisted ones if present 
    }); 

Quindi, in base a ciò che si trova, è possibile "correggere" gli argomenti della funzione in modo che corrispondano.

59

I metodi promessi legacy $httpsuccess e error sono stati deprecati. Utilizzare invece il metodo standard then. Dai un'occhiata ai documenti https://docs.angularjs.org/api/ng/service/ $ http

Ora la strada giusta da usare è:

// Simple GET request example: 
$http({ 
    method: 'GET', 
    url: '/someUrl' 
}).then(function successCallback(response) { 
    // this callback will be called asynchronously 
    // when the response is available 
    }, function errorCallback(response) { 
    // called asynchronously if an error occurs 
    // or server returns response with an error status. 
}); 

L'oggetto risposta ha queste proprietà:

  • dati - {string | oggetto} - Il corpo di risposta trasformato con le funzioni di trasformazione.
  • stato - {numero} - codice di stato HTTP della risposta.
  • intestazioni - {function ([headerName])} - Funzione getter intestazione.
  • config - {Object} - L'oggetto di configurazione utilizzato per generare la richiesta.
  • statusText - {string} - Testo di stato HTTP della risposta.

Un codice di stato di risposta tra 200 e 299 è considerato uno stato di successo e determinerà il richiamo della chiamata di successo.

+0

L'unica risposta corretta ... –

Problemi correlati