在'Router'类型中,属性'path'不存在,角度为2?

时间:2017-02-08 09:17:19

标签: angular typescript

我是Angular 2中的新手,并创建了一个演示应用。我在做同样的事情时遇到了这个错误。我想我在下面的代码中做错了什么:

  canLoad(router: Router): boolean {
      let url = `/${router.path}`;
      return this.checkLogin(url);
    }

请建议我,我做错了什么?在上面的代码中我认为,path不是router的属性,我知道但是同样的属性是什么?

完整代码 -

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

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }


  canLoad(router: Router): boolean {
  let url = `/${router.path}`;
  return this.checkLogin(url);
}

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

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

    // Create a dummy session id
    let sessionId = 123456789;

    // Set our navigation extras object
    // that contains our global query params and fragment
    let navigationExtras: NavigationExtras = {
      queryParams: { 'shubhamsession_id': sessionId },
      fragment: 'shubhamanchor'
    };

    // Navigate to the login page with extras
    this.router.navigate(['/login'], navigationExtras);
    return false;
  }
}

1 个答案:

答案 0 :(得分:1)

如果您想获取网址,请注入RouterStateSnapshot而不是Router

canLoad(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url = state.url;
    return this.checkLogin(url);
}

https://angular.io/docs/ts/latest/guide/router.html