首页 > 解决方案 > 如何在第一个函数和第二个 canActivate() 中执行

问题描述

我有这个 AuthGuard。在这段代码中,我想创建一个条件。如果我的resetpasss 不为null,我想在ResetPassIdComponent 中导航,否则我想在LoginFirstComponent 中导航。

为此,我创建了 AuthGuard。

export class AuthGuard implements CanActivate {
    myappurl: any;
    resetpasss: any;
    constructor(private router: Router, private auth: LoginService) {
    }
    geturl() {
        handleOpenURL((appURL: AppURL) => {
            console.log('Got the following appURL1', appURL);
            this.myappurl = appURL
            let url_1 = this.myappurl.toString();
            let url_id = url_1.split("/").reverse()[0];
            this.resetpasss = url_id
            let LS = require("nativescript-localstorage");
            LS.setItem(this.resetpasss)
            // this.router.navigateByUrl('/resetPasswordRequest/' + this.resetpasss);
            console.log('this.resetpass1', this.resetpasss)
        });
        return true;
    }
    canActivate(): boolean {
        this.geturl();
        if (this.auth.isAuthenticated()) {
            return true;
        }
        console.log('this.resetpasss2', this.resetpasss)
        this.router.navigate(['/outsidelogin/login']);
        return false;
    }
 }

我单击电子邮件中的链接,此链接显示在geturl(){..}. 从这个函数geturl(){..}我得到一个 id 并保存在 localstorage 中。现在在 canActivate() 中,我想创建一个条件,在我想要的组件中导航。

你能问我如何创造条件吗?

我的路由.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 }
];

标签: angulartypescriptnativescriptcanactivate

解决方案


您可以在CanActivate()本身中添加条件。你可以像下面这样尝试吗?

canActivate(): boolean {
    this.geturl();
    if (this.auth.isAuthenticated()) {
        return true;
    } else if(this.resetpasss){
       this.router.navigate([this.myappurl]);
    }else{
        this.router.navigate(['/outsidelogin/login']);
    }       
}

推荐阅读