在Angular2中实现动态路由(打字稿) [英] Implementing Dynamic Routing in Angular2 (Typescript)

查看:248
本文介绍了在Angular2中实现动态路由(打字稿)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RouteConfig类(可用于通过路由功能装饰组件(@RouteConfig))具有为该组件定义的某些路由定义.现在,要抓住的是要在运行时(动态)注入这些路由定义.

RouteConfig class which can be used to decorate a component (@RouteConfig) with routing capabilities has certain route definitions defined for that component. Now, the catch is to have these route definitions injected at runtime (dynamically).

原因是,假设我有一个应用程序,其中我必须显示(UI)并定义(装饰)"n"个路由,每个路由对应于为其加载应用程序的帐户,并因此对应于与该特定帐户相关联.因此,在装饰器@RouteConfig中为组件预定义路由定义没有任何意义.

The reason being, let's say I have an application wherein I have to display (UI) and define (decorate) 'n' number of routes, each which corresponds to the account for which the application is loaded and consequently the rights that are associated with that particular account. Thus, having the route definitions pre-defined in the decorator @RouteConfig for a component doesn't make any sense.

我的方法是每次加载新帐户时都要进行服务呼叫.并且仅检索关联的路由并在运行时将其注入,以便导航到与该帐户的UI中显示的每个路由相对应的其他各个组件.

My approach is to make a service call every time a new account is loaded. And retrieve the associated routes only and inject them during runtime so as to navigate to other respective components corresponding to each route displayed in the UI for that account.

import { Summary } from './components/summary';

@RouteConfig([
  /*
    Let's say we need a seller dashboard to be displayed...
  */
  //{ path: 'SellerDashboard', component: SellerDashboard }
  { path: '/', component: Summary }
])
class App {
    contactInfo: ContactInfoModel;
    public App(dataService: DataService) {
        this.model = dataService.getContactInfo();
    }
}

在上面的代码段中,假设我希望加载与抢劫到我的应用程序中的卖方帐户相对应的卖方仪表板.现在,显示销售点"仪表板或与卖方无关的任何内容都没有任何意义(在我们的案例中,卖方的库存仪表板与卖方相关).

In the code snippet above, lets say I wish to load the seller dashboard corresponding to a seller account looged in to my application. Now, it won;t make any sense to display the Point of Sales dashboard or anything thats not relevant to a seller (In our case, seller's inventory dashboard is relevant to a seller).

要点在于,仅注入所需的那些路由,而不是在同一位置配置所有路由.

这个问题的用例或场景比这篇文章上标记的重复使用的情况要简单(此问题随后被提出).这篇文章中提到的答案具有更简单的方法,也更加直观.

This question has a simple use case or a scenario than the duplicate marked on this post (which was asked afterwards). The answers mentioned in this post have simpler approaches and are far more intuitive, too.

推荐答案

检查此帖子:

http://blog .mgechev.com/2015/12/30/angular2-router-dynamic-route-config-definition-creation/

基本上,作者创建了一个类DynamicRouteConfigurator,该类使用Reflect API将路由动态添加到@RouteConfig装饰器.

Basically the author creates a class DynamicRouteConfigurator that uses the Reflect API to dynamically add routes to the @RouteConfig decorator.

Github链接:

https://github. com/mgechev/dynamic-route-creator/blob/master/app/components/app/app.ts

这篇关于在Angular2中实现动态路由(打字稿)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆