使用canActivate()时如何在另一个组件中进行路由

时间:2018-12-25 08:44:20

标签: angular routing nativescript canactivate

当我使用canActivate()时,我想直接在此处的组件ResetPassIdComponent中导航;现在,当我单击该组件ResetPassIdComponent时,我的应用程序先进入/outsidelogin/login,然后进入resetPasswordRequest/:id

export class AuthGuard implements CanActivate {
    constructor(private router: Router, private auth: LoginService) { }
    canActivate(): boolean {
        if (this.auth.isAuthenticated()) {
            return true;
        }
        this.router.navigate(['/outsidelogin/login']);
        return false;
    }
}

因此,在此canActivate()中,我有2个条件,首先是如果我登录,然后是第二个条件(如果未登录),请在this.router.navigate(['/outsidelogin/login']);中导航

我的routing.ts

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: 'fp', component: FirstPageComponent
      }
    ]
  },
  {
    path: 'outsidelogin',
    component: outsideloginComponent,
    children: [
      { path: 'login', component: LoginFirstComponent },
      { path: 'register', component: RegisterComponent },
    ]
  },
    { path: '', redirectTo: '/home/fp', pathMatch: 'full' },
    { path: 'resetPasswordRequest/:id', component: ResetPassIdComponent }
];

请,您能和我分享任何想法,如何解决我的问题吗?

1 个答案:

答案 0 :(得分:0)

首先,您需要在resetPasswordRequest /:id中获取参数,如果登录后按如下所示获取参数并将字符串转换为数字。您必须将身份验证令牌存储在浏览器缓存中。

    // import in resetPasswordeRquest Component.
    import { Route, AcivatedRoute } from '@angular/router'; 

    // inside component class;
    id: number;
    constructor(private router: Router, private route: ActivatedRoute){
       this.route.paramMap.subscribe(params => {
          this.id = +params.get('id');   
       }           
    }