How to use routing in Angular? This article will show you how to use routing in Angular and get you started quickly with Angular routing. I hope it will be helpful to you!
The concept of routing has been widely used in the front-end framework. I will not elaborate on the thoughts of routing. The application of routing is nothing more than nesting and passing parameters. More advanced functions such as lazy loading, preloading, and more advanced functions such as routing guards, etc. In this article, we will take a look at how to use routing in Angular. [Related tutorial recommendations: "angular tutorial"]
Create project & first-level module:
ng new angular-router-sample
ng g c pages/login
ng g c pages/home
ng g c pages/mine
Note: Components created through cli will be automatically registered.
in the html template of the App to configure routing jumps & routing exits (
router- outlet
)
<div> <a [routerLink]="['/login']">登陆</a>| <a [routerLink]="['/home']">首页</a>| <a [routerLink]="['/mine']">我的</a> </div> <!-- 配置路由出口 --> <router-outlet></router-outlet>
The simplest component routing A path (routing Url) attribute and a component (Url corresponding to the loaded component) attribute are necessary:
const routes: Routes = [ { path: 'login', component: LoginComponent, }, { path: 'home', component: HomeComponent, }, { path: 'mine', component: MineComponent, }, ];
When we accidentally access a non-existent How to configure our 404 page when using URL?
path supports a special wildcard to support "**". When there is no successful match in the routing table, it will finally point to the component corresponding to the wildcard
const routes: Routes = [ ... { path: '**', component: NotFountComponent, }, ];
Note: The router matching policy is first come first served, so unspecific routing configurations are configured later.
Since our project has no specific route matching after default startup, which is not friendly, we need to set a valid default route route to display to the user.
The configured default route should be above the wildcard route.
const routes: Routes = [ ... { path: '', redirectTo: '/home', pathMatch: 'full' }, ... ];
At this time our routing configuration is all
app-routing
, this is of course feasible for simple applications, but with the iteration of applications and the increase of modules, it is obvious that configuring them together is a challenge for management and expansion, and the split of modules becomes inevitable.
Create a module configuration with routing for the Home component through cli:
ng generate module pages/home/home --module app --flat --routing
imports: [ BrowserModule, HomeRoutingModule, AppRoutingModule, ]
Note: Modules created with cli will be automatically configured to the root module, but we can adjust it manually Move the AppRoutingModule to the end in the following order to satisfy the first-come, first-served policy.
home-routing
const routes: Routes = [{ path: 'home', component: HomeComponent, }];
Note: After configuration, you can put the app The Home component configuration in -routing
has been removed.
Execute the command to create the subcomponents
##ng g c pages/home/children/user-list
ng g c pages/home/children/user-detail
ng g c pages/home/children/edit-user
to the Home router configuration childrenproperty to configure sub-component routing
const routes: Routes = [{ ... children: [ { path: 'list', component: UserListComponent, }, { path: 'detail', component: UserDetailComponent, }, { path: 'edit', component: EditUserComponent, }, { path: '', redirectTo: '/home/list', pathMatch: 'full' } ] }];
<div> <a [routerLink]="['/home/list']">列表</a>| <a [routerLink]="['/home/edit']">编辑</a>| <a [routerLink]="['/home/detail']">详情</a> </div> <!-- 配置路由出口 --> <router-outlet></router-outlet>
/:key
{ path: 'detail/:id', component: UserDetailComponent }
routerLink
<a [routerLink]="['/hero', hero.id]">
Before usingActivatedRoute
, you must inject it into the target component
方式1: 获取参数(路由参数变化可以被监听,适用于同一组件实例多次复用的情况)
this.route.paramMap.subscribe( (params: ParamMap) => { console.log('id :>> ', params.get('id')); } )
方式2: 获取参数(只获取到初始值)
const id = this.route.snapshot.paramMap.get('id')!;
ParamMap API:
成员 | 说明 |
---|---|
has(name) | 如果参数名位于参数列表中,就返回 true 。 |
get(name) | 如果这个 map 中有参数名对应的参数值(字符串),就返回它,否则返回 null 。如果参数值实际上是一个数组,就返回它的第一个元素。 |
getAll(name) | 如果这个 map 中有参数名对应的值,就返回一个字符串数组,否则返回空数组。当一个参数名可能对应多个值的时候,请使用 getAll 。 |
keys | 返回这个 map 中的所有参数名组成的字符串数组。 |
当前组件注入Router对象
无参数携带跳转:
this.router.navigate(['/home/list']);
携带参数跳转:
this.router.navigate(['/home/list', { id: this.userId, name: this.userName }]);
注:矩阵URL标记法:;id=101;name=bom
懒加载的目的是将模块的挂载延迟到我们使用的时候,避免首次打开页面就进行整体加载导致页面长时间不可用。
对路由进行分组而不增加额外的路径片段
{ path: 'home', loadChildren: () => import('./pages/home/home.module').then((m) => m.HomeModule), }
微调
home-routing
中home组件的path配置为""
const routes: Routes = [{ path: '', component: HomeComponent, children: [ ... ] }];
angular中配置懒加载后模块的加载被延迟到来使用时,但是有一些组件是需要优先加载并在使用的时候可以及时运行。
angular中的Router模块提供来两种预加载的策略:
完全不预加载,这是默认值。惰性加载的特性区仍然会按需加载。
预加载所有惰性加载的特性区。
修改方式:RouterModule.forRoot()的参数二的对象支持设置加载模式的属性preloadingStrategy
,
PreloadAllModules: 预加载有所模块
NoPreloading: 默认,不进行预加载
这么鸡肋的属性必须要支持自定义,我们来看一下:
在需要预加载的路由配置对象中添加data对象并增加preload
属性,值设置为true
表示开启预加载。
通过cli来生成一个服务用来完成我们的预加载策略:ng generate service selective-preloading-strategy
将我们创建的服务实现接口PreloadingStrategy
自定义的策略和默认支持的两种策略使用方法一致。
import { Injectable } from '@angular/core'; import { PreloadingStrategy, Route } from '@angular/router'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class SelectivePreloadingStrategyService implements PreloadingStrategy { preloadedModules: string[] = []; preload(route: Route, fn: () => Observable<any>): Observable<any> { // 通过检查路由配置来决定是否做预加载 if (route.data && route.data.preload && route.path != null) { // 参数1: 要加载的路由 this.preloadedModules.push(route.path); // 参数2: 加载器 return fn(); } else { return of(null); } } }
以上就是最近对Angular路由的学习整理,对于路由还有一块守卫没有提到,我们抽时间再来整理一下。
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of A brief discussion on how to use routing in Angular?. For more information, please follow other related articles on the PHP Chinese website!