我的应用程序中有两个状态 - / auth和/ masters。后者是我想在他或她经过身份验证后才引导用户的状态。
所以,我知道我们可以使用' $ urlRouterProvider.otherwise'将应用程序中的默认状态配置为/ auth。所以foll是我的代码:
angular.module('ngClassifieds', ['ngMaterial', 'ui.router', 'firebase'])
.config(function($mdThemingProvider, $stateProvider, $urlRouterProvider) {
$mdThemingProvider
.theme('default')
.primaryPalette('blue-grey')
.accentPalette('orange');
$urlRouterProvider.otherwise('/auth');
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'components/auth/auth.tpl.html',
controller: 'authCtrl'
})
$stateProvider
.state('masters', {
url: '/masters',
templateUrl: 'components/classifieds.tpl.html',
controller: 'classifiedsCtrl'
});
});
现在,如果我输入除了/ masters以外的任何东西,我将被导向/ auth;但是,如果我输入/掌握,我不会被导向/ auth。
我了解到我需要在Firebase(https://www.firebase.com/docs/web/libraries/angular/guide/user-auth.html)中查找AUTH_REQUIRED错误以获得所需的结果。但是,我觉得在尝试整合功能时,我的体重超过了我的体重。如果你能给我一些指导,我会很感激。这就是我试图重构上面代码的方法,但它是一团糟:
angular.module('ngClassifieds', ['ngMaterial', 'ui.router', 'firebase'])
.run(["$rootScope", "$state", function($rootScope, $state) {
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
// We can catch the error thrown when the $requireAuth promise is rejected
// and redirect the user back to the home page
if (error === "AUTH_REQUIRED") {
$state.go("auth");
}
});
}]);
.config(function($mdThemingProvider, $stateProvider, $urlRouterProvider) {
$mdThemingProvider
.theme('default')
.primaryPalette('blue-grey')
.accentPalette('orange');
$urlRouterProvider.otherwise('/auth');
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'components/auth/auth.tpl.html',
controller: 'authCtrl',
resolve: {
// controller will not be loaded until $waitForAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["Auth", function(Auth) {
// $waitForAuth returns a promise so the resolve waits for it to complete
return Auth.$waitForAuth();
}]
}
})
$stateProvider
.state('masters', {
url: '/masters',
templateUrl: 'components/classifieds.tpl.html',
controller: 'classifiedsCtrl',
resolve: {
// controller will not be loaded until $requireAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["Auth", function(Auth) {
// $requireAuth returns a promise so the resolve waits for it to complete
// If the promise is rejected, it will throw a $stateChangeError (see above)
return Auth.$requireAuth();
}]
}
});
});