[Angular2 Router] Configuring a Home Route and Fallback Route - Learn An Essential Routing Concept

本文介绍如何配置 Angular 2 路由器来处理常见的路由场景,包括根路径显示主页及未知 URL 的行为。通过示例代码讲解如何设置首页路由和兜底路由。

In this tutorial we are going to learn how to configure the Angular 2 router to cover some commonly used routing scenarios: what if the user goes to the root of the application manually ? Probably you would want some sort of home page to be displayed. Also another very common scenario is: what should be the behaviour of the application when an unknown url is accessed? We are already know that in the server everything is getting redirected to the index.html file, so how do we handle this on the client?

We are going to answer those questions by learning how to configure the angular 2 router to have both an index or home route, and a fallback route. We are also going to learn an essential concept about routing configuration.

 

app.routes.ts:

import {RouterModule} from "@angular/router";
import {NotFoundComponent} from "./shared-components/not-found/not-found.component";

const indexRoute = {path: '', loadChildren: 'app/home/home.module'};
const fallbackRoute = {path: '**', component: NotFoundComponent};
const routes = [
  {path: 'home', loadChildren: 'app/home/home.module', name: 'Home'},
  {path: 'heros', loadChildren: 'app/heros/heros.module', name: 'Heros'},
  {path: 'contact', loadChildren: 'app/contact/contact.module', name: 'Contact'},
  indexRoute,
  fallbackRoute
];

export default RouterModule.forRoot(routes);

 

Notice here, the order does matter, if put fallbackRoute to the first place, it will error out.

 

Github

转载于:https://www.cnblogs.com/Answer1215/p/5910571.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值