【问题标题】:Dynamic build routes {or dynamic component import} Angular 2 [duplicate]动态构建路线{或动态组件导入}Angular 2 [重复]
【发布时间】:2016-07-20 22:33:48
【问题描述】:

也许有人知道如何动态构建路由(或者只是动态导入组件)。

例如:

我的 JSON 包含具有 RouteName、路径、ComponentNames(字符串)的对象。 我想迭代它并动态构建路由定义(路由配置)。但我不知道,如何进行动态组件导入。 我可以将字符串“ComponentName”从 JSON 传递给导入规则,因为导入需要静态定义(从谷歌搜索中找到了一些问题)。

失败

let a = "MyComponentName"
import {a} from ......     

(我想出的一个想法 - its like create some map key-value, and keep into key - route, value - Component, and after that equals routename from JSON and my MAP and push needed component into final route config array. But its 如此丑陋的解决方案)也许还有另一种方式存在?

我卡住了。非常感谢您的帮助.....

【问题讨论】:

    标签: dynamic import routes angular components


    【解决方案1】:

    您可以利用 Async 路由来执行此操作。根据您的路由配置,您可以从模块加载路由。在这种情况下,您需要添加模块路径以获取与路由关联的组件。

    这是一个示例:

    var routes = {
      path: '/path',
      name: 'some name',
      module: './my.component',
      component: 'MyComponentName'
    }
    routes.forEach((route : any) => {
      this.routeConfigArray.push(
          new AsyncRoute({
              path : route.path,
              loader : () => System.import(route.module).then(m => m[route.component]),
              name : route.name
          });
      );
    });
    
    this._router.config(this.routeConfigArray);
    

    另一种方法是添加一个函数来获取函数的名称。基于此,您可以检查您是否有匹配的潜在组件。

    这是一个示例:

    ngOnInit() {
      this.routes = [
        {
          path: '/test', component: 'OtherComponent', name: 'Test'
        }
      ];
      this.configureRoutes(this.routes);
      this.router.config( this.routes);
    }
    
    configureRoutes(routes) {
      var potentialComponents = [ OtherComponent ];
      routes.forEach((route) => {
        route.component = potentialComponents.find((component) => {
          return component.name === route.component;
        });
      });
    }
    

    看到这个 plunkr:https://plnkr.co/edit/KKVagp?p=preview

    查看这个问题了解更多详情:

    【讨论】:

    • 每当我尝试添加多个路线时,我都无法让它工作。 this.routes = [ {路径:'/test',组件:'OtherComponent',名称:'Test'},{路径:'/test2',组件:'OtherComponent2',名称:'Test2'}];跨度>
    【解决方案2】:

    https://github.com/angular/angular/issues/11437#issuecomment-245995186 提供了一个RC.6 Plunker

    更新

    在新的路由器(>= RC.3https://angular.io/docs/js/latest/api/router/index/Router-class.html#!#resetConfig-anchorresetConfig可以使用

    router.resetConfig([
     { path: 'team/:id', component: TeamCmp, children: [
       { path: 'simple', component: SimpleCmp },
       { path: 'user/:name', component: UserCmp }
     ] }
    ]);
    

    原创

    应该做的是

    import from 'myComponents' as myComponents;
    
    ...
    
    someFunc(name:string) {
      console.debug(myComponents[name]);
    }
    

    可以使用加载路线

    constructor(private router:Router) { }
    
    someFunc() {
      this.router.config([
        { 'path': '/', 'component': IndexComp },
        { 'path': '/user/:id', 'component': UserComp },
      ]);
    }
    

    我自己没试过。

    另请参阅此相关问题Angular2 App Routing through Services

    【讨论】:

    • 看起来不错。谢谢)
    • 似乎也支持更新单个组件的路由。
    【解决方案3】:

    说。 page1、page2 和 page3 三个屏幕和 app/page1.ts、app/page2.ts 和 app/page3.ts 的组件

           let screens : Array<string> = ["Page1","Page2","Page3"];
           let aRouter : RouteDefinition;
           this.routes = new Array<RouteDefinition>();
           screens.map(function(screenId){
               aRouter = new AsyncRoute({
                    path: "/" + screenId,
                    name: screenId,
                    loader: () =>  System.import("app/" + screenId).then(c => c[screenId]) // not  import {page1, page2, page3}}
                });
                this.routes.push(aRouter);
           }.bind(this));  //we need to bind to current "this" instead of global this
            this.router.config(this.routes);
    

    trick 是 .bind(this),它是 vanella javscript 对于整个解决方案,请检查此 动态加载 Angular 2 异步路由器 https://github.com/Longfld/DynamicalAsyncRouter

    【讨论】:

    • 不鼓励仅链接的答案。请将相关部分直接添加到答案中(代码示例、解释、...)
    猜你喜欢
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2017-05-20
    • 2017-07-07
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2019-08-30
    相关资源
    最近更新 更多