Folgende ist meine Strecke KonfigurationWinkelauflösung Route - deferred.reject nicht funktioniert - Angular 1 + Typoskript
function routes($routeProvider: ng.route.IRouteProvider) {
let accessResolver = ['UserFactory', (UserFactory: any) => {
return UserFactory.isAuthenticated();
}];
//Configuring routes
$routeProvider.when('/', {
templateUrl: '/views/home.html',
controller: 'HomeController',
controllerAs: 'homeCtrl',
resolve: accessResolver
}).when('/login', {
templateUrl: '/views/login.html',
controller: 'LoginController',
controllerAs: 'loginCtrl'
}).otherwise({
redirectTo: '/'
});
}
Und Fehler meiner Route ändern Handler
function run($rootScope: ng.IRootScopeService, $location: ng.ILocationService) {
$rootScope.$on("$routeChangeError",() => {
console.log("Route Change Error");
$location.url('/login?redirect=' + $location.url());
});
}
Und die Userfactory
module TheHub {
export interface IUserFactory {
isAuthenticated(): ng.IDeferred<String>;
}
class UserFactory implements IUserFactory {
constructor(private $http: ng.IHttpService, private $q: ng.IQService, private $rootScope: any) {
}
isAuthenticated(): ng.IDeferred<String> {
let deferred = this.$q.defer();
if (this.$rootScope.auth && this.$rootScope.auth.isAuthenticationChecked) {
if (this.$rootScope.auth.isAuthenticated) {
deferred.resolve('OK');
} else {
deferred.reject('Unauthorized');
}
} else {
this.$http.get('secure/user').then(
(response: ng.IHttpPromiseCallbackArg<{}>) => {
if (!this.$rootScope.auth) {
this.$rootScope.auth = {};
}
this.$rootScope.auth.isAuthenticationChecked = true;
this.$rootScope.auth.isAuthenticated = true;
deferred.resolve('OK');
},
(error: any) => {
if (!this.$rootScope.auth) {
this.$rootScope.auth = {};
}
this.$rootScope.auth.isAuthenticationChecked = true;
deferred.reject('Unauthorized');
});
}
return deferred;
}
}
function userFactory($http: ng.IHttpService, $q: ng.IQService, $rootScope: any) {
return new UserFactory($http, $q, $rootScope);
}
userFactory.$inject = ['$http', '$q', '$rootScope'];
angular.module('TheHub').factory('UserFactory', userFactory);
}
Die Logik hier ist, ich feuere eine Anfrage zu überprüfen, ob der Benutzer bereits angemeldet ist und eine Sitzung hat. Das Problem ist, wenn der Benutzer nicht bereits angemeldet ist, der Dienst fehlschlägt und das Versprechen wird abgelehnt. Aber ich bin mir nicht sicher, warum der Handler $ routeChangeError nicht ausgelöst wird. Es funktioniert gut, wenn ein JavaScript-Fehler vorliegt.
Sie müssen 'zurückkehren verwenden deferred.promise', aber Sie sollten wirklich vollständig [vermeiden, dass die latenten Antipattern] (http://stackoverflow.com/ q/23803743/1048572) – Bergi
Vielen Dank .. das war ein dummer Fehler .. Kannst du das als Antwort posten, damit ich es auflösen kann .. – Pavan