Angular 2路由器导航到url但仍然呈现源组件

时间:2017-01-22 19:49:47

标签: angular angular2-routing

我正在尝试使用Angular 2创建一个身份验证系统,我使用angular2-jwt并且一切正常,但我遇到的问题是当未经验证的用户尝试访问受限制的路由时,处理此我检查如果用户在ngOnInit()函数中进行了身份验证,如果没有,则应该将用户重定向到登录页面,在我的情况下,url会更改,但它仍会呈现acced组件模板,这是我的代码:

import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";

import {UserService} from "../services/user.service";

@Component({
  selector: 'app-home',
  templateUrl: '../templates/home.component.html',
  styleUrls: ['../../assets/styles/home.component.css']
})
export class HomeComponent implements OnInit {

full_name: string;
constructor(private userService: UserService, private router: Router){}

ngOnInit() {
  if(this.userService.isTokenExpired()){
    this.router.navigate([''])
  }else{
    this.userService.getSessionData()
      .subscribe(
        data => {
          let usrData = data.data.user;
          localStorage.setItem('user', JSON.stringify(usrData));
          this.full_name = usrData.firstname+" "+usrData.lastname;
          if(usrData.role == 'admin'){
            this.router.navigate(['admin']);
          }
        },
        err => console.log(err)
      );
    }
  }
}

这是它的外观:

enter image description here 您可以注意到没有数据。

令人厌恶的是,另一个组件(AdminComponent)中的相同代码工作正常。

这是我的 app.routes.ts 文件:

import {Routes} from "@angular/router";

import {AdminComponent} from "./components/admin.component";
import {LoginComponent} from "./components/login.component";
import {HomeComponent} from "./components/home.component";
import {GroupsComponent} from "./components/groups.component";
import {TpComponent} from "./components/tps.component";
import {TraineeComponent} from "./components/trainee.component";
import {RegisterComponent} from "./components/register.component";
import {HometpsComponent} from "./components/hometps.component";

export const routes: Routes = [
  { path: '', component: LoginComponent},
  { path: 'login', component: LoginComponent},
  { path: 'register', component: RegisterComponent},
  { path: 'admin', component: AdminComponent, children: [
    { path: '',
      redirectTo: '/admin/tps',
      pathMatch: 'full'},
    { path: 'tps', component: TpComponent},
    { path: 'groupes', component: GroupsComponent},
    { path: 'stagiaires', component: TraineeComponent}
  ]},
  { path: 'home', component: HomeComponent, children: [
    { path: '',
      redirectTo: '/home/tps',
      pathMatch: 'full'},
    { path: 'tps', component: HometpsComponent},
  ]},
  { path: '**', component: LoginComponent}
];

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:0)

似乎我的路由工作正常,问题出现在我的子组件HometpsComponent' ngOnInit()中,我从localStorage读取数据(如果用户未登录或者他的会话有,则为空已过期),它会生成错误并阻止路由器导航。

谢谢。