How to get unresolved path from browser in Angular

2019-07-13 17:33发布

问题:

This might be a weird situation but please bear with me - We generally incorporate a feature in Angular Apps that any unresolved path should go to Home Page. Is there a way to get the value of that unresolved path?

I am using routing to divert any unresolved path to Login. Once successfully logged in user is taken to Home page. But I want to also capture that wrong path and make some decision based upon this. How can I do this?

My router file looks like this:

export const ROUTES: Routes = [
  { path: '', redirectTo: 'app', pathMatch: 'full' },
  { path: 'app',   loadChildren: () => System.import('./layout/layout.module') },
  { path: 'login', loadChildren: () => System.import('./login/login.module') },
  { path: 'auth', loadChildren: () => System.import('./auth/auth.module')},
  { path: 'error', component: ErrorComponent },
  { path: '**',    redirectTo: 'login', canActivate: [AuthGuard] }
];

and AuthGuard service is:

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

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router: Router) {}

  // On clicking a route or entering a URL in the address bar, check
  // whether the user is logged in and can proceed to the route.
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    return this.checkLogin(url);
  }

  // On clicking a sub-route, check whether the user is logged in.
  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }

  // If the user is logged in, he can proceed to the intended route.
  // If he's not logged in, redirect him to the login page.
  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    }

    // Store the attempted URL for redirecting after logging in
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/login']);

    return false;
  }
}