【问题标题】:How to change router paths programmatically?如何以编程方式更改路由器路径?
【发布时间】:2019-05-25 00:42:34
【问题描述】:

我正在使用 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 吗?

【问题讨论】:

  • 我脑海中浮现的第一个想法是路由守卫,但我发现了一篇有趣的文章可以满足您的需求:medium.com/@davidgolverdingen/…,祝您一切顺利

标签: javascript angular typescript ionic-framework


【解决方案1】:

这不是针对此类要求更改应用程序路由文件的正确方法。 您可以使用 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;
    }

    }); 


  }


}


【讨论】:

    猜你喜欢
    • 2017-09-03
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多