Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Angular 4.x Route

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shares with you the content of a sample analysis of Angular 4.x routing. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Installing the router

First of all, we need to install Angular Router. You can do this by running any of the following:

Yarn add @ angular/router# ORnpm I-- save @ angular/router

After the above command is executed, the @ angular/router module will be automatically downloaded to the node_modules folder.

Base href

The last thing we need to do is add tags to our index.html file. Routing needs to determine the root directory of the application based on this. For example, when we go to http://example.com/page1, if we do not define the underlying path of the application, the route will not know whether the managed address of our application is http://example.com or http://example.com/page1.

This is easy to do, just open the index.html file in the project and add the appropriate tags, as follows:

Application

The above configuration information tells Angular routing that the root directory of the application is /.

Using the router

To use routing, we need to import RouterModule in the AppModule module. The details are as follows:

Import {NgModule} from'@ angular/core';import {BrowserModule} from'@ angular/platform-browser';import {RouterModule} from'@ angular/router';import {AppComponent} from'. / app.component';@NgModule ({imports: [BrowserModule, RouterModule], bootstrap: [AppComponent], declarations: [AppComponent]}) export class AppModule {}

Our routing is not working properly at this time because we have not configured information about application routing. The RouterModule object provides us with two static methods: forRoot () and forChild () to configure routing information.

RouterModule.forRoot ()

The RouterModule.forRoot () method is used to define the main routing information in the main module, and by calling this method, our main module can access all the instructions defined in the routing module. Let's take a look at how to use forRoot ():

/ /... import {Routes, RouterModule} from'@ angular/router';export const ROUTES: Routes = []; @ NgModule ({imports: [BrowserModule, RouterModule.forRoot (ROUTES)], / /...}) export class AppModule {}

Instead of directly using RouterModule.forRoot ([...]), we define the configuration information for the route using const, and then call the RouterModule.forRoot () method as a parameter. The advantage of this approach is that it makes it easier for us to export ROUTES to other modules when needed.

RouterModule.forChild ()

RouterModule.forChild () is similar to the Router.forRoot () method, but it can only be applied to feature modules.

Tip: forRoot () is used in the root module and forChild () is used in the submodule.

This is very powerful because we don't have to define all routing information in one place (our main module). Instead, we can define module-specific routing information in the feature module and import them into our main module if necessary. RouterModule.forChild () is used as follows:

Import {NgModule} from'@ angular/core';import {CommonModule} from'@ angular/common';import {Routes, RouterModule} from'@ angular/router';export const ROUTES: Routes = []; @ NgModule ({imports: [CommonModule, RouterModule.forChild (ROUTES)], / /...}) export class ChildModule {}

Through the above example, we know that in the main module and the feature module, the type of routing configuration object is the same, except that the main module and the feature module need to call different methods to configure module routing. Let's take a look at how to configure the ROUTES object.

Configuring a route

All the routes we define are as objects in the ROUTES array. First, define a route for our home page:

Import {Routes, RouterModule} from'@ angular/router';import {HomeComponent} from'. / home/home.component';export const ROUTES: Routes = [{path:'', component: HomeComponent}]; @ NgModule ({imports: [BrowserModule, RouterModule.forRoot (ROUTES)], / /.}) export class AppModule {}

In the example, we define the matching path of the route through the path attribute, while the component attribute is used to define the components that need to be loaded when the route matches.

Tip: we use path:''to match an empty path, for example: https://yourdomain.com

Displaying routes

After configuring the routing information, the next step is to use an instruction called router-outlet to tell Angular where to load the component. When the Angular route matches the response path and successfully finds the component that needs to be loaded, it dynamically creates the corresponding component and inserts it into the router-outlet element as a sibling element.

In our AppComponent component, we can insert router-outlet instructions anywhere:

Import {Component} from'@ angular/core';@Component ({selector: 'app-root', template: `Our app `}) export class AppComponent {}

Now that we have established the primary route for the application, we can learn more about other configuration options for routing.

Further configuration

What we have introduced so far is just the beginning, let's take a look at some other options and features.

Dynamic routes

It is of little use if the route is always static. For example, path:''is the static route that loads our HomeComponent component. We will introduce dynamic routing. Based on dynamic routing, we can render different pages according to different routing parameters.

For example, if we want to display different user information based on different user names on the profile page, we can define routes in the following ways:

Import {HomeComponent} from'. / home/home.component';import {ProfileComponent} from'. / profile/profile.component';export const ROUTES: Routes = [{path:'', component: HomeComponent}, {path:'/ profile/:username', component: ProfileComponent}]

The key point here is that it tells the Angular route that: username is the routing parameter, not the actual part of the URL.

Tip: if: is not used, it will be used as a static route and will only match the / profile/username path

Now that we have established a dynamic route, the most important thing at this time is how to get the routing parameters. To access the information about the current route, we need to first import ActivatedRoute from the @ angular/router module, then inject the object into the constructor of the component class, and finally obtain the routing parameters by subscribing to the object's params attribute. Examples are as follows:

Import {Component, OnInit} from'@ angular/core';import {ActivatedRoute} from'@ angular/router';@Component ({selector: 'profile-page', template: `{{username}}`}) export class SettingsComponent implements OnInit {username: string; constructor (private route: ActivatedRoute) {} ngOnInit () {this.route.params.subscribe ((params) = > this.username = params.username);}}

After introducing dynamic routing, let's explore how to create a child routes.

Child routes

In fact, every route supports child routes. Suppose there are / settings/profile and / settings/password pages under our / settings settings page, which represent the profile page and the password modification page, respectively.

We might want our / settings page to have its own component, and then display the / settings/profile and / settings/password pages in the setup page component. We can do this:

Import {SettingsComponent} from'. / settings/settings.component';import {ProfileSettingsComponent} from'. / settings/profile/profile.component';import {PasswordSettingsComponent} from'. / settings/password/password.component';export const ROUTES: Routes = [{path: 'settings', component: SettingsComponent, children: [{path:' profile', component: ProfileSettingsComponent}, {path: 'password', component: PasswordSettingsComponent}]}] @ NgModule ({imports: [BrowserModule, RouterModule.forRoot (ROUTES)],}) export class AppModule {}

Here, we define two child routes in the setttings route that will inherit the path of the parent route, so the route matching address of the change password page is / settings/password, and so on.

The last thing we need to do next is to add the router-outlet instruction to our SettingsComponent component because we want to present the child routes in the settings page. If we did not add the router-outlet directive to the SettingsComponent component, although / settings/password matches the routing address of the password change page, the password change page will not display properly. The specific code is as follows:

Import {Component} from'@ angular/core';@Component ({selector: 'settings-page', template: ``}) export class SettingsComponent {}

Component-less routes

Another useful routing feature is component-less routing. Using component-less routes allows us to group routes together and have them share routing configuration information and outlet.

For example, we can define setttings routes without using the SettingsComponent component:

Import {ProfileSettingsComponent} from'. / settings/profile/profile.component';import {PasswordSettingsComponent} from'. / settings/password/password.component';export const ROUTES: Routes = [{path: 'settings', children: [{path:' profile', component: ProfileSettingsComponent}, {path: 'password', component: PasswordSettingsComponent}]}]; @ NgModule ({imports: [BrowserModule, RouterModule.forRoot (ROUTES)],}) export class AppModule {}

At this point, the contents of the / settings/profile and / settings/password route definitions are displayed in the router-outlet element of the AppComponent component.

LoadChildren

We can also tell the route to get the child route from another module.

Let's create a SettingsModule module to hold all setttings-related routing information:

Import {NgModule} from'@ angular/core';import {CommonModule} from'@ angular/common';import {Routes, RouterModule} from'@ angular/router';export const ROUTES: Routes = [{path:', component: SettingsComponent, children: [{path: 'profile', component: ProfileSettingsComponent}, {path:' password', component: PasswordSettingsComponent}]}]; @ NgModule ({imports: [CommonModule, RouterModule.forChild (ROUTES)],}) export class SettingsModule {}

It is important to note that we use the forChild () method in the SettingsModule module because SettingsModule is not the main module of our application.

Another major difference is that we set the primary path of the SettingsModule module to an empty path (''). Because if our path is set to / settings, it will match / settings/settings, which is obviously not what we want. By specifying an empty path, it matches the / settings path, which is what we want.

So where does / settings routing information need to be configured? The answer is in AppModule. At this point, we need to use the loadChildren attribute, as follows:

Export const ROUTES: Routes = [{path: 'settings', loadChildren:'. / settings/settings.module#SettingsModule'}]; @ NgModule ({imports: [BrowserModule, RouterModule.forRoot (ROUTES)], / /...}) export class AppModule {}

It is important to note that instead of importing SettingsModule into our AppModule, we tell the Angular route through the loadChildren attribute to load the SettingsModule module according to the path configured by the loadChildren attribute. This is the specific application of the lazy loading function of the module. When the user visits the / settings/** path, the corresponding SettingsModule module will be loaded, which reduces the size of loading resources when the application starts.

In addition, we pass a string as the property value of loadChildren, which consists of three parts:

Relative path to import module is required

# delimiter

Export the name of the module class

After understanding some of the advanced options and features of routing, let's introduce routing instructions.

Router Directives

In addition to the router-outlet instruction, some other instructions are provided in the routing module. Let's see how they can be used in conjunction with what we introduced earlier.

RouterLink

In order for us to link to the route we have set up, we need to use the routerLink directive, as shown in the following example:

Home Change password Profile Settings

When we click on any of the above links, the page will not be reloaded. Instead, our path will be displayed in the URL address bar, followed by subsequent view updates to match the values set in routerLink.

Friendly tip: we can also change the attribute value of routerLink to an array so that we can pass specific routing information.

If we want to link to a dynamic routing address that has a routing variable for username, we can configure the attribute value for routerLink as follows:

Go to {{username}}'s profile.

RouterLinkActive

In actual development, we need to let the user know which route is active, which is usually achieved by adding a class to the active link. In order to solve the above problems, the Angular routing module provides us with routerLinkActive instructions, and an example of the use of this instruction is as follows:

Home Change password Profile Settings

By using the routerLinkActive directive, the active class is automatically added to the an element when the route corresponding to the an element is active.

Finally, let's give a brief introduction to Router API.

Router API

We can achieve the same function as routerLink through the API also provided by routing. To use Router API, we need to inject the Router object into the component class, as follows:

Import {Component} from'@ angular/core';import {Router} from'@ angular/router';@Component ({selector: 'app-root', template: `Our app `}) export class AppComponent {constructor (private router: Router) {}}

There is a navigate () method in the injected router object in the component class, which supports the same parameter type as the routerLink directive, and when this method is called, the page will automatically jump to the corresponding routing address. Specific examples are as follows:

Import {Component, OnInit} from'@ angular/core';import {Router} from'@ angular/router';@Component ({selector: 'app-root', template: `Our app `}) export class AppComponent implements OnInit {constructor (private router: Router) {} ngOnInit () {setTimeout (() = > {this.router.navigate ([/ settings']);}, 5000);}}

If the above code runs successfully, the user interface will be redirected to the / settings page after 5 seconds. This method is very useful, such as automatically redirecting to the login page when it is detected that the user has not logged in.

Another example of use is to demonstrate how to pass data when a page jumps, as follows:

Import {Component, OnInit} from'@ angular/core';import {Router} from'@ angular/router';@Component ({selector: 'app-root', template: `Users `}) export class AppComponent implements OnInit {users: Username [] = [{name:' toddmotto', id: 0}, {name: 'travisbarker', id: 1}, {name:' tomdelonge', id: 2}] Constructor (private router: Router) {} handleSelect (event) {this.router.navigate (['/ profile', event.name]);}}

I have something to say.

Is there any other way to navigate a page other than using the navigate () method?

Angular Router API provides us with navigate () and navigateByUrl () methods for page navigation. Then why are there two different ways?

Using the router.navigateByUrl () method is the same as directly changing the URL address on the address bar, we use a new URL address. However, the router.navigate () method produces a new URL address based on a series of input parameters. To better distinguish the differences between them, let's look at an example, assuming that the current URL address is:

/ inbox/11/message/22 (popup:compose)

When we call the router.navigateByUrl ('/ inbox/33/message/44') method, the URL address becomes / inbox/33/message/44. But if we are calling the router.navigate ('/ inbox/33/message/44') method, the current URL address will become / inbox/33/message/44 (popup:compose).

Thank you for reading! This is the end of the article on "sample Analysis of Angular 4.x routing". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report