是否可以在角度2中动态建立添加路由? [英] Is it possible to build add routes dynamically in angular 2?

查看:54
本文介绍了是否可以在角度2中动态建立添加路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个cms,用户可以在其中选择要使用的页面.因此,如果用户想要联系页面,则可以选择它并为其填写一些内容,例如,他们的站点将具有contact路由.基于此,是否可以根据用户是否想要特定页面来动态添加角度路由?

解决方案

是.有多种方法可以满足您的需求.您可以使用router.resetConfig用新的配置重置路由器的配置:

this.router.resetConfig([
 { path: 'somePath', component: SomeComponent},
 ...
]);

您还可以push路由至配置:

this.router.config.push({ path: 'somePath', component: SomeComponent });

我执行此操作的另一种方法是,我使用户可以使用TinyMCE之类的东西来构建页面并指定他们希望页面具有的url路径.在Angular中,我使用{ path: '**', component: ComponentBuilder }在路由器中指定了通配符路由,其中​​ComponentBuilder组件将从数据库中获取与某人请求的路径相对应的模板,然后使用该模板动态生成该组件.如果数据库中不存在模板,则将呈现普通的Page cannot be found模板.

两种方法都有效.这取决于您希望应用程序如何运行以及如何构建用户创建的页面.

自从我在版本2 rc4中提出解决方案以来,还有更多关于如何创建动态组件的文档和示例.我没有使用任何这些,但看起来很有帮助:

用于动态组件的NPM软件包

动态组件加载程序上的角度文档

动态创建组件

关于动态创建组件的另一篇文章

I am building a cms where a user can pick what pages to use. So if the user wants a contact page, they select it and fill out some content for it and their site would have a contact route for example. Based on this, is it possible to dynamically add routes in angular based on if a user wants or does not want a particular page?

解决方案

Yes. There are multiple ways to accomplish what you are wanting. You can use router.resetConfig to reset the router's config with a new config:

this.router.resetConfig([
 { path: 'somePath', component: SomeComponent},
 ...
]);

You can also push routes onto the config:

this.router.config.push({ path: 'somePath', component: SomeComponent });

Another way I've done this is I had made a way users could build pages using something like TinyMCE and specify the url path they wanted the page to have. In Angular, I specified a wild-card route in the router with { path: '**', component: ComponentBuilder }, where the ComponentBuilder component would fetch the template from the database that corresponds to the path someone requested and then dynamically generate the component with the template. If a template didn't exist in the database, then a normal Page cannot be found template was rendered.

Both ways work. It comes down to how you want your application to function and how you will build the pages users create.

There is a lot more documentation and examples on how to create dynamic components since the solution I came up with in version 2 rc4. I have not used any of these, but it looks helpful:

NPM package for Dynamic Components

Angular Docs on Dynamic Component Loader

Dynamically Creating Components

Another article on dynamically creating components

这篇关于是否可以在角度2中动态建立添加路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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