路由器:从`canActivate`方法返回的promise中重定向

时间:2016-09-27 09:44:29

标签: javascript angular angular2-routing

我有几种方法可以访问我的服务器。所有这些方法都没有返回promises或observable,我正在传递回调。

现在我需要写一个保护,确保在用户可以使用多个路由之前加载了用户数据。 canActivate方法返回一个promise,但是有一些代码可以在该promise中导航,但不起作用。

有人知道如何解决这个问题。我是否必须重写我的api方法才能返回承诺或obervables?或者有没有办法从承诺中进行重定向,返回我的canActivate。移动代码以获取用户数据(如果用户已登录)到解析对象中会更好吗?

import {Injectable} from '@angular/core';
import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {GlobalStateService} from './globalState.service';
import {AuthTokenService} from './authToken.service';
import {UserApi} from '../api/user.api';

@Injectable()
export class AfterLogInGuardService implements CanActivate {

    constructor(
        private globalState: GlobalStateService,
        private authToken: AuthTokenService,
        private router: Router,
        private userApi: UserApi
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean|Promise<boolean> {

        // The tho user is not logged in, redirect her always to the login page, if
        // she calls routes with this guard.
        if (!this.authToken.has()) {
            this.router.navigateByUrl('/logIn');
            return false;
        }

        const thisGuard = this;

        // If the user has a token, we have to ensure, that we have the user data
        // loaded from the server.
        return this.afterUserDataHasBeenLoaded(function () {

            // Redirect the user to the "Please enter your personal data" page, if
            // she has not entered them yet.
            if (!thisGuard.globalState.personalDataStored && route.url.toString() !== 'signUp,personalData') {

                //
                // This here doesn't work!
                //

                thisGuard.router.navigateByUrl('/signUp/personalData');
                return false;
            }
            return true;
        });
    };

    private afterUserDataHasBeenLoaded(callback: () => boolean) {

        const thisGuard = this;

        return new Promise<boolean>(function(resolve, reject) {

            if (thisGuard.globalState.userDataLoaded)
                return callback();

            const innerCallback = function () {
                thisGuard.globalState.userDataLoaded = true;
                resolve(callback());
            };

            thisGuard.userApi.getUserData(innerCallback);
        });
    }
}

1 个答案:

答案 0 :(得分:0)

实施后可能很有用。 Promise在auth.service中定义

<强> auth.guard

difftime(end_time, start_time);

<强> auth.service

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService} from './services/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
      status:boolean=false;
      constructor(private authService:AuthService, private router:Router) { }
      canActivate() {
        var self=this;
        this.authService.isAuth()
        .then((res)=>{if(res==true)return true;else self.router.navigate(['/login']);});
      }
    }

服务器响应

  

{_ body:“{”status“:false}”,状态:200,ok:true,statusText:“OK”,   标题:标题......}