官术网_书友最值得收藏!

Setting up the application and its routing

Now that we have the base code set up, let's list the steps for us to build an app that will enable us to create a custom Back button in a browser:

  1. Creating states for the application.
  2. Recording when the state of the application changes.
  3. Detecting a click on our custom Back button.
  4. Updating the list of the states that are being tracked.

Let's quickly add a few states to the application, which are also known as routes in AngularAll SPA frameworks have some form of routing module, which you can use to set up a few routes for your application.

Once we have the routes and the routing set up, we will end up with a directory structure, as follows:

Directory structure after adding routes

Now let's set up the navigation in such a way that we can switch between the routes. To set up routing in an Angular application, you will need to create the component to which you want to route and the declaration of that particular route. So, for instance, your home.component.ts would look as follows:

import { Component } from '@angular/core';

@Component({
selector: 'home',
template: 'home page'
})
export class HomeComponent {

}

The home.routing.ts file would be as follows:

import { HomeComponent } from './home.component';

export const HomeRoutes = [
{ path: 'home', component: HomeComponent },
];

export const HomeComponents = [
HomeComponent
];

We can set up a similar configuration for as many routes as needed, and once it's set up, we will create an app-level file for application routing and inject all the routes and the navigatableComponents in that file so that we don't have to touch our main module over and over.

So, your file app.routing.ts would look like the following:

import { Routes } from '@angular/router';
import {AboutComponents, AboutRoutes} from "./pages/about/about.routing";
import {DashboardComponents, DashboardRoutes} from "./pages/dashboard/dashboard.routing";
import {HomeComponents, HomeRoutes} from "./pages/home/home.routing";
import {ProfileComponents, ProfileRoutes} from "./pages/profile/profile.routing";

export const routes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
...AboutRoutes,
...DashboardRoutes,
...HomeRoutes,
...ProfileRoutes
];

export const navigatableComponents = [
...AboutComponents,
...DashboardComponents,
...HomeComponents,
...ProfileComponents
];

You will note that we are doing something particularly interesting here:

{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}

This is Angular's way of setting default route redirects, so that, when the app loads, it's taken directly to the /home path, and we no longer have to set up the redirects manually.

主站蜘蛛池模板: 聂荣县| 墨竹工卡县| 乐东| 铁力市| 赣州市| 阳信县| 孝昌县| 启东市| 双江| 永昌县| 博湖县| 哈巴河县| 呼和浩特市| 鄂伦春自治旗| 双辽市| 赤峰市| 长宁县| 江达县| 新丰县| 光泽县| 收藏| 万年县| 大埔区| 南丰县| 子洲县| 温州市| 绥德县| 奉贤区| 库尔勒市| 衡山县| 泸水县| 安泽县| 汉川市| 柳江县| 南江县| 瑞丽市| 万盛区| 定结县| 安岳县| 安阳县| 寿宁县|