2014-07-07 12 views
9


Ho un app angolare JS con un back-end vele JS, e all'interno dei percorsi (in app.js) ho:

.state('app.detail', { 
    url: "/detail", 
    views: { 
    'menuContent' :{ 
     templateUrl: "templates/detail.html", 
     controller: 'UserUpdateCtrl', 
     resolve: { 
     auth: ["$q", "userData", function($q, userData) { 
      var userInfo = userData.getUserInfo(); 
      if (userInfo) { 
      return $q.when(userInfo); 
      } else { 
      return $q.reject({ authenticated: false }); 
      } 
     }] 
     }, 
    } 
    } 
}) 

(questo sta seguendo this guide)

Ora sullo stesso file, ho il $ routeChangeError:

.run(function($rootScope) { 
    $rootScope.$on("$routeChangeError", function(event, current, previous, eventObj) { 
    if (eventObj.authenticated === false) { 
     $location.path("/login"); 
    } 
    }); 

Quando debug su chrome, vedo che la funzione è definita, ma non chiamata.
Cosa mi manca qui?

+0

forse non hai < ui-view >? –

+5

Sicuro che vuoi '$ stateChangeError' ... – ivarni

+0

Ok sta chiamando' $ stateChangeError' ma la variabile 'eventObj.authenticated' non è definita (eventObj:' Object {name: "", url: "^", visualizzazioni: null , abstract: true} ') – Asaf

risposta

9

Ok, supponendo che si stia utilizzando il router UI angolare, credo che si stia semplicemente traducendo erroneamente il gestore degli errori da quello ufficiale.

Dal docs for $state:

Fired when an error occurs during transition. It's important to note that if you have any errors in your resolve functions (javascript errors, non-existent services, etc) they will not throw traditionally. You must listen for this $stateChangeError event to catch ALL errors.

E i parametri per questo gestore sono diversi, provare qualcosa di simile:

$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) { 
    if (error && !error.authenticated) { 
    $location.path("/login"); 
    } 
}); 

Ecco una descrizione dei parametri con l'importante in grassetto:

  • evento - {oggetto} - oggetto evento.
  • toState - {State} - Lo stato di transizione a.
  • toParams - {Object} - I parametri forniti al toState.
  • fromState - {State} - Lo stato corrente, pre-transizione.
  • fromParams - {Object} - I parametri forniti da fromState.
  • errore - {Errore} - L'oggetto errore di risoluzione.
+0

Tutto funziona tranne il '$ location.path' che per qualche motivo non reindirizza (la parte del percorso è corretta se questo aiuta) – Asaf

+3

Come on man c'è uno schema qui con i tuoi problemi, stai usando $ state invece di $ posizione . Leggi i documenti, probabilmente dovrebbe essere '$ state.go()' o qualcosa del genere. – Terry

+1

Grazie mille, a volte angularjs mi fa dimenticare come funziona la logica di base. – Asaf

Problemi correlati