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

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.

主站蜘蛛池模板: 龙州县| 宝坻区| 始兴县| 乡宁县| 越西县| 长岭县| 九龙县| 大埔区| 日照市| 富宁县| 闽侯县| 广丰县| 兴仁县| 苏尼特左旗| 锦屏县| 丘北县| 吉木乃县| 高州市| 潼南县| 安顺市| 紫阳县| 沿河| 莎车县| 沅陵县| 皮山县| 同德县| 五河县| 婺源县| 榆社县| 体育| 固阳县| 普洱| 天柱县| 唐河县| 全南县| 丹阳市| 安平县| 新田县| 新余市| 信阳市| 独山县|