简体   繁体   中英

Router: Redirect from within a promise returned by a `canActivate` method

I have several methods to access my server. All of those methods don't return promises or observables, I'm passing callbacks in.

Now I need to write a guard, that ensures, that user data has been loaded before the user can use several routes. The canActivate method returns a promise, but there is code to navigate away within that promise and that does not work.

Has anybody an idea how to fix this. Do I have to rewrite my api methods to return promises or obervables? Or is there a way to make a redirect from with a promise, that is returned my canActivate . Would it be better, to move the code to fetch the user data (if a user is logged in) into a resolve object?

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);
        });
    }
}

Following Implementation can be Useful. Promise is defined in auth.service

auth.guard

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

auth.service

isAuth(): Promise<Status> {
  const url = "/account/check";
  return this.http.get(url)
    .toPromise()
    .then(response=>return response.json().status as Status)
    .catch(this.handleError);
}

Server Response

{_body: "{"status":false}", status: 200, ok: true, statusText: "OK", headers: Headers…}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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