如何以编程方式更改路由器路径?

费德里科

我正在使用Angular构建Ionic应用程序,并调用API以获得一些结果。根据响应对象的特定属性(例如“ mode” =“ 0”或mode =“ 1”),我需要更改在应用程序路由模块中定义的路径,尤其是要动态更改主页。

我希望appcomponent(启动组件)调用API并检查模式,然后根据该属性传递一些路由。

例如:

我想要类似的东西:

  if (mydata['mode']==="0") {
   this.appRoutes = [
    {
    path: '',
    redirectTo: 'firstPath',
    pathMatch: 'full'
    },
    {
    path: 'firstPath',
    loadChildren: './firstpath.module#FistPathModule'
    },
    {
    path: 'secondPath',
    loadChildren: './secondpath.module#SecondPathModule'
    }
  ]
 } else if (my_data['mode']==="1") {
   this.appRoutes = [
    {
    path: '',
    redirectTo: 'secondPath',
    pathMatch: 'full'
    },
    {
    path: 'secondPath',
    loadChildren: './secondpath.module#SecondPathModule'
    },
  ]
 }

有没有办法在app-routing.module内部做类似的事情?在第二种情况下也可以隐藏firstPath吗?

莫希特·萨克森纳(Mohit Saxena)

对于这种要求,这不是更改应用程序路由文件的正确方法。您可以使用Guard来实现这一点。

In your child route file do like this: 
 {
        path: '',
        component: HomePage,
        canActivate: [AuthGuard]
      }


Auth Guard file: 

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  mode: number;  **// You can save this mode variable into a common service and use it.**
  constructor() { }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {

    if(this.mode == 1) {
      return false;
    }else {
      return true;
    }

    }); 


  }


}


本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章