如何从Angular 2中的浏览器获取未解决的路径?

时间:2017-04-20 12:43:50

标签: angular typescript angular2-routing

这可能是一个奇怪的情况,但请耐心等待 - 我们通常在Angular Apps中加入一个功能,任何未解决的路径都应该转到主页。有没有办法获得未解决路径的价值?

我正在使用路由将任何未解析的路径转移到Login。成功登录后,用户将进入主页。但是我想要抓住错误的道路并根据这个做出一些决定。我怎么能这样做?

我的路由器文件如下所示:

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

和AuthGuard服务是:

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

0 个答案:

没有答案