【问题标题】:How to execute in first a function and in second canActivate()如何在第一个函数和第二个 canActivate() 中执行
【发布时间】:2018-12-25 10:33:38
【问题描述】:

我有这个 AuthGuard。在这段代码中,我想创建一个条件。如果我的 resetpasss 不为空,我想在这里导航 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 }
];

【问题讨论】:

  • handleOpenURL异步吗?
  • 控制台有错误吗?
  • this.resetpasss2 未定义
  • @ArtyomAmiryan 询问您的 handleOpenURL() 是异步的吗?

标签: angular typescript nativescript canactivate


【解决方案1】:

您可以在 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']);
    }       
}

【讨论】:

  • 是的,但是当我单击链接时如何在此组件 ResetPassIdComponent 中直接导航?
  • this.resetpasss 未定义,直接在this.router.navigate(['/outsidelogin/login']);中导航
  • 你能看到我的演示吗 github.com/binaau/auth_guard 安装后,请点击这个链接 stackoverflow.com/questions/53921510 并使用应用程序打开。此时,您可以看到该应用程序首先在登录组件中导航,然后在重置通道中进行第二次导航。我只想在单击链接时直接在重置通道中导航。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 2021-08-21
  • 2016-05-02
相关资源
最近更新 更多