简体   繁体   English

角度路由解析-deferred.reject不起作用-角度1 + TypeScript

[英]Angular route resolution - deferred.reject not working - Angular 1 + TypeScript

Following is my route configuration 以下是我的路线配置

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: '/'
        });
    }

And my route change error handler 还有我的路线更改错误处理程序

function run($rootScope: ng.IRootScopeService, $location: ng.ILocationService) {
        $rootScope.$on("$routeChangeError", () => {
            console.log("Route Change Error");
            $location.url('/login?redirect=' + $location.url());
        });
    }

And the UserFactory 和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);
}

The logic here is, I am firing a request to check if the user is already logged in and has a session. 这里的逻辑是,我触发一个请求以检查用户是否已经登录并具有会话。 The problem is, when the user is not logged in already, the service is failing and the promise is getting rejected. 问题是,当用户尚未登录时,服务将失败,并且承诺将被拒绝。 But, I am not sure why, the handler $routeChangeError is not being fired. 但是,我不确定为什么不触发处理程序$ routeChangeError。 It is working fine when there is a JavaScript error. 出现JavaScript错误时,它工作正常。

You've forgotten the .promise so that you only returned the deferred, which was neither awaited nor the resolution value you expected. 您已经忘记了.promise因此您只返回了延迟的.promise ,既没有等待,也没有期望的分辨率值。

But you should avoid the deferred antipattern anyway - just do 但是无论如何,您都应该避免使用延迟的反模式 -只需这样做

isAuthenticated(): ng.IPromise<String> {
    if (this.$rootScope.auth && this.$rootScope.auth.isAuthenticationChecked) {
        if (this.$rootScope.auth.isAuthenticated) {
            return this.$q.resolve('OK');
//          ^^^^^^^^^^^^^^^^^^^^^^
        } else {
            return this.$q.reject('Unauthorized');
//          ^^^^^^^^^^^^^^^^^^^^^^
        }
    } else {
        return 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;
                return 'OK';
//              ^^^^^^
            },
            (error: any) => {
                if (!this.$rootScope.auth) {
                    this.$rootScope.auth = {};
                }
                this.$rootScope.auth.isAuthenticationChecked = true;
                return this.$q.reject('Unauthorized');
//              ^^^^^^^^^^^^^^^^^^^^^
            }
        );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM