Table of Contents
Angular Routing (Route)
Single-page application (SPA)
Routing object
Routes array
RouterOutlet Router Outlet
组件的内容显示在(Detailed explanation of Route routing in Angular-outlet)下方
Router Router
RouterLink Router link
ActivatedRoute activated route
在路由时传递数据
重定向路由
子路由
辅助路由
路由守卫(guard)
CanActivate/CanActiveChild:处理导航到某路由的情况
CanDeactivate:处理从当前路由离开的情况
Resolve:在路由激活之前获取路由数据
Home Web Front-end JS Tutorial Detailed explanation of Route routing in Angular

Detailed explanation of Route routing in Angular

Apr 15, 2021 am 10:39 AM
angular route routing

This article will take you through the routing (Route) in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of Route routing in Angular

Angular Routing (Route)

We can understand the Detailed explanation of Route routing in Angular as a view object that controls the state of the entire application. Each application There is a Detailed explanation of Route routing in Angular; another function of the Detailed explanation of Route routing in Angular is to assign a unique URL to each view. This URL can be used to jump between applications to a specific view state. A single-page application is actually a collection of view states.

Related tutorial recommendations: "angular tutorial"

Single-page application (SPA)

A single-page application is the homepage The page is only loaded once and does not refresh repeatedly. It is an application that only changes part of the content of the page. Angular applications are single-page applications that use Detailed explanation of Route routing in Angulars in Angular to change the content of the page based on user operations without reloading the page. A single-page application can be understood as a collection of view states.

Routing object

Detailed explanation of Route routing in Angular

Routes array

The Detailed explanation of Route routing in Angular needs to be configured first Have routing information, and use the RouterModule.forRoot method to configure the Detailed explanation of Route routing in Angular. When the browser's URL changes, the Detailed explanation of Route routing in Angular looks up the corresponding Route and decides which component to display based on that.
Basic configuration:

const appRoutes: Routes = [
  { path: 'common/a', component: AComponent },
  { path: 'common/b/:id', component: BComponent },
  { path: '**', component: NotFoundComponent}, // 定义通配符路由
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  ...
})
Copy after login
RouterOutlet Router Outlet

RouterOutlet is a directive from the routing module, its usage is similar to a component. It acts as a placeholder to mark a location in the template where the Detailed explanation of Route routing in Angular will display the component to be displayed at this outlet.

 <h1 id="组件的内容显示在-Detailed-explanation-of-Route-routing-in-Angular-outlet-下方">组件的内容显示在(Detailed explanation of Route routing in Angular-outlet)下方</h1>
 <Detailed explanation of Route routing in Angular-outlet></Detailed explanation of Route routing in Angular-outlet>
Copy after login
Router Router

Use the Router object to navigate.

constructor(private Detailed explanation of Route routing in Angular: Router) {}

toAComponent() {
    this.Detailed explanation of Route routing in Angular.navigate([&#39;/common/a&#39;]);
    // 或 this.Detailed explanation of Route routing in Angular.navigateUrl(&#39;common/a&#39;);
}
Copy after login

Route link url must start with ‘/’.

<a [Detailed explanation of Route routing in AngularLink]="[&#39;/&#39;]">主页</a>
<a [Detailed explanation of Route routing in AngularLink]="[&#39;/common/b&#39;, id]">B组件</a>
<Detailed explanation of Route routing in Angular-outlet></Detailed explanation of Route routing in Angular-outlet>
Copy after login
ActivatedRoute activated route

The path and parameters of the currently activated route can be obtained through the routing service of ActivateRoute.

  • Commonly used attributes:
    AttributesDescription
    urlThe Observable object of the routing path is a string array composed of various parts in the routing path.
    dataAn Observable, Contains the data object provided to the route. Also contains values ​​resolved by the resolve guard.
    paramMapAn Observable that contains a map object consisting of the required and optional parameters of the current route. Use this map to get a single value or multiple values ​​from a parameter with the same name.
    queryParamMapAn Observable containing a map object consisting of query parameters that are valid for all routes. Use this map to get a single value or multiple values ​​from a query parameter.
在路由时传递数据
  • 在查询参数中传递数据

/common/b?id=1&name=2 => ActivatedRoute.queryParamMap

  • 在路由路径中传递数据

{path: /common/b/:id} => /commo/b/1 => ActivatedRoute.paramMap

  • 在路由配置中传递数据

{path: /common/b, component: BComponent, data: {id:“1”, title: “b”}}

  • 示例
constructor(
    private activatedRoute: ActivatedRoute
) { }

ngOnInit() {
   // 从参数中获取
    this.activatedRoute.queryParamMap.subscribe(params => {
      this.id = params.get(&#39;id&#39;);
    });

   // 或
  // this.activated.snapshot.queryParamMap.get(&#39;id&#39;);

    // 从路径中获取
    this.activatedRoute.paramMap.subscribe(params => {
      this.id = params.get(&#39;id&#39;);
    });

    this.activatedRoute.data.subscribe(({id,title}) => {

    });
}
Copy after login

snapshot: 参数快照,是一个路由信息的静态快照,抓取自组件刚刚创建完毕之后,不会监听路由信息的变化。如果确定一个组件不会从自身路由到自身的话,可以使用参数快照。

subscribe: 参数订阅,相当于一个监听器,会监听路由信息的变化。

重定向路由

在用户访问一个特定的地址时,将其重定向到另一个指定的地址。
配置重定向路由:

// 当访问根路径时会重定向到 home 路径
const appRoutes: Routes = [
  { path: &#39;&#39;, redirectTo: &#39;home&#39;, pathMatch: &#39;full&#39;},
  { path: &#39;home&#39;, component: HomeComponent}
];
Copy after login

子路由

子路由配置语法:

const appRoutes: Routes = [
  { 
    path: &#39;home&#39;, 
    component: HomeComponent,
    children: [
      { path: &#39;&#39;, component: AComponent},
      { path: &#39;b&#39;, component: BComponent}
    ]
  },
];
Copy after login

辅助路由

辅助路由又兄弟路由,配置语法:

// 路由配置
{path: &#39;xxx&#39;, component: XxxComponent, outlet:&#39;xxxlet&#39;},
{path: &#39;yyy&#39;, component: XxxComponent, outlet:&#39;yyylet&#39;}

// 使用
<Detailed explanation of Route routing in Angular-outlet></Detailed explanation of Route routing in Angular-outlet>
<Detailed explanation of Route routing in Angular-outlet name="xxxlet"></Detailed explanation of Route routing in Angular-outlet>

// 链接
<a [Detailed explanation of Route routing in AngularLink]="[&#39;/home&#39;,{outlets:{xxxlet: &#39;xxx&#39;}}]">Xxx</a>
Copy after login

当点击Xxx链接时,主插座会显示’/home’链接所对应的组件,而xxxlet插座会显示xxx对应的组件。

路由守卫(guard)

CanActivate/CanActiveChild:处理导航到某路由的情况

当用户不满足这个守卫的要求时就不能到达指定路由。

export class DemoGuard1 implements CanActivate {

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    ...
    return true;
  }
}
Copy after login

CanDeactivate:处理从当前路由离开的情况

如果不满足这个守卫的要求就不能离开该路由。

// 泛型中 AComponent 代表要守卫的组件。
export class DemoGuard2 implements CanDeactivate<AComponent> {
 canDeactivate(component: AComponent): boolean {
   // 根据 component 的信息进行具体操作
   retturn true;
 }
}
Copy after login

Resolve:在路由激活之前获取路由数据

在进入路由时就可以立刻把数据呈现给用户。

@Injectable()
export AResolve implements Resolve<any> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
     const id = route.paramMap.get(&#39;id&#39;);
     // 可以根据路由中的信息进行相关操作
  }
}
Copy after login

最后,需要将路由守卫添加到路由配置中:

const appRoutes: Routes = [
  { 
    path: &#39;common/a&#39;, 
    component: AComponent,
    canActivate: [DemoGurad1],
    canDeactivate: [DemoGuard2],
    resolve: {data: AResolve}
   },
  { path: &#39;common/b/:id&#39;, component: BComponent },
  { path: &#39;**&#39;, component: NotFoundComponent}, // 定义通配符路由
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  ...
})
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Detailed explanation of Route routing in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Java Apache Camel: Building a flexible and efficient service-oriented architecture Java Apache Camel: Building a flexible and efficient service-oriented architecture Feb 19, 2024 pm 04:12 PM

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

How to implement API routing in the Slim framework How to implement API routing in the Slim framework Aug 02, 2023 pm 05:13 PM

How to implement API routing in the Slim framework Slim is a lightweight PHP micro-framework that provides a simple and flexible way to build web applications. One of the main features is the implementation of API routing, allowing us to map different requests to corresponding handlers. This article will introduce how to implement API routing in the Slim framework and provide some code examples. First, we need to install the Slim framework. The latest version of Slim can be installed through Composer. Open a terminal and

Use JavaScript functions to implement web page navigation and routing Use JavaScript functions to implement web page navigation and routing Nov 04, 2023 am 09:46 AM

In modern web applications, implementing web page navigation and routing is a very important part. Using JavaScript functions to implement this function can make our web applications more flexible, scalable and user-friendly. This article will introduce how to use JavaScript functions to implement web page navigation and routing, and provide specific code examples. Implementing web page navigation For a web application, web page navigation is the most frequently operated part by users. When a user clicks on the page

How to use routing in ThinkPHP6 How to use routing in ThinkPHP6 Jun 20, 2023 pm 07:54 PM

ThinkPHP6 is a powerful PHP framework with convenient routing functions that can easily implement URL routing configuration; at the same time, ThinkPHP6 also supports a variety of routing modes, such as GET, POST, PUT, DELETE, etc. This article will introduce how to use ThinkPHP6 for routing configuration. 1. ThinkPHP6 routing mode GET method: The GET method is a method used to obtain data and is often used for page display. In ThinkPHP6, you can use the following

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

Implementation method and experience summary of flexibly configuring routing rules in PHP Implementation method and experience summary of flexibly configuring routing rules in PHP Oct 15, 2023 pm 03:43 PM

Implementation method and experience summary of flexible configuration of routing rules in PHP Introduction: In Web development, routing rules are a very important part, which determines the corresponding relationship between URL and specific PHP scripts. In the traditional development method, we usually configure various URL rules in the routing file, and then map the URL to the corresponding script path. However, as the complexity of the project increases and business requirements change, it will become very cumbersome and inflexible if each URL needs to be configured manually. So, how to implement in PHP

See all articles