1. Basic use of routing
-
1. Create two components
ng g c components/home ng g c components/news Copy the code
-
2. Configure routes in app-routing.module.ts
const routes: Routes = [ // Default access address { path: ' ', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'news', component: NewsComponent }, // The home route is sent when there is no match { path: '* *', redirectTo: 'home', pathMatch: 'full'}];Copy the code
-
3. Use route hops
<ul> <li> <a routerLink="home">Home page</a> </li> <li> <a routerLink="news">news</a> </li> </ul> <! -- Routing switch slot --> <router-outlet></router-outlet> Copy the code
Two, several route jump way
-
1. Method 1: Direct use
<a routerLink="home">Home page</a> Copy the code
-
2. Dynamic transfer of values
<a [routerLink] ="[ '/home' ]">Home page</a> Copy the code
3. Route selection style
<a routerLink="home" routerLinkActive="active">Home page</a>
Copy the code
Dynamic routing
-
1. Configure the routing file
. { path:'news', component: NewsComponent }, { path: 'news/:id', component: DetailComponent }, ... Copy the code
-
2. Configure route forwarding
<ul> <li *ngFor="let item of articleList"> <a [routerLink] ="['/news', item.id]">{{item.title}}</a> <! -- < a routerLink = "/ news / {{item. Id}}" > jump to details < / a > -- > </li> </ul> Copy the code
-
3. Obtain the value passed by the dynamic route
import { ActivatedRoute } from '@angular/router'; .private sub: any; constructor(private readonly route: ActivatedRoute) {} ngOnInit() { console.log(this.route); this.sub = this.route.params.subscribe((params: any) = > { console.log(params); }); // Use snapshot to take a snapshot of the route. console.log(this.route.snapshot.paramMap.get('id')); } ngOnDestroy() { this.sub.unsubscribe(); }}Copy the code
Fifth, usequery
Passing parameters
-
1. Route redirection
<a [routerLink] ="['news']" [queryParams] ="{ id: 1, name: 'hello', age: 20 }" routerLinkActive="active" >news</a > Copy the code
-
2. Obtain routing parameters from the component
import { ActivatedRoute } from '@angular/router'; export class NewsComponent implements OnInit, OnDestroy { public sub: any; constructor(private readonly route: ActivatedRoute) {} ngOnInit() { this.sub = this.route.queryParams.subscribe(data= > { console.log(data); }); } ngOnDestroy() { this.sub.unsubscribe(); }}Copy the code
Six, injs
Middle route jump
-
1. Jump without parameters
import { Router } from '@angular/router'; export class DetailComponent implements OnInit, OnDestroy { private sub: any; constructor(private readonly router: Router) {} public goHome() { this.router.navigate(['/home']); }}Copy the code
-
2. Jump with Parameters (dynamic routing)
import { ActivatedRoute, Router } from '@angular/router'; export class NewsComponent implements OnInit, OnDestroy { constructor(private readonly router: Router) {} public detail(): void { this.router.navigate(['/news'.'2']); }}Copy the code
-
3. Jump with query parameter
import { ActivatedRoute, Router, NavigationExtras } from '@angular/router'; .public goHome() { const navigationExtras: NavigationExtras = { / / query parameters queryParams: { name: 'hello', age: 20 }, fragment: 'aaa' / / the anchor }; this.router.navigate(['/home'], navigationExtras); } Copy the code
7. Nesting of routes
-
1. Configure routes
const routes: Routes = [ { path: 'home', component: HomeComponent, children: [ { path: 'add', component: AddComponent }, { path: 'edit', component: EditComponent } ] }, ... ] Copy the code
-
2. Configure route forwarding
<p> <a [routerLink] ="['/home/add']" routerLinkActive="active">Add content</a> </p> <p> <a [routerLink] ="['/home/edit']" routerLinkActive="active">Edit content</a> </p> Copy the code
Routing and lazy loading module
-
1. Create two modules and corresponding components
Ng g m pages/home --routing # create module ng g m pages/user --routing #Create components ng g c pages/home ng g c pages/user ng g c pages/user/login ng g c pages/user/components/login ng g c pages/user/components/infomation Copy the code
-
2. Main route
const routes: Routes = [ { path: ' ', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', loadChildren: './pages/home/home.module#HomeModule' }, { path: 'userInfo', loadChildren: './pages/user/user.module#UserModule' }, { path: '* *', loadChildren: './pages/home/home.module#HomeModule'}];Copy the code
-
2. Route to home
const routes: Routes = [ { path: ' ', redirectTo: 'index', pathMatch: 'full' }, { path: 'index', component: HomeComponent }, { path: '* *', redirectTo: 'index', pathMatch: 'full'}];Copy the code
-
3. User routes
const routes: Routes = [ { path: ' ', redirectTo: 'user', pathMatch: 'full' }, { path: 'user', component: UserComponent, children: [ { path: 'login', component: LoginComponent }, { path: 'user_info', component: InfomationComponent } ] }, { path: '* *', redirectTo: 'user', pathMatch: 'full'}];Copy the code
9. Module preloading
The above module is lazy loading, so it will not load all the data after entering the page, and the current data will be loaded only after the user clicks the page, but this often has a disadvantage (some data is not available at the beginning, and will appear after waiting). To solve this wait, we can preload
-
PreloadAllModules (NoPreloading by default)
import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule {} Copy the code
-
2. Method 2. Preload the corresponding module according to your own configuration
-
Configure routes to be preloaded
const routes: Routes = [ { path: 'home', loadChildren: './pages/home/home.module#HomeModule', data: { preload: true } }, { path: 'userInfo', loadChildren: './pages/user/user.module#UserModule', data: { preload: true}}];Copy the code
-
Create your own my-preloading-strategy.ts
import { Route, PreloadingStrategy } from '@angular/router'; import { Observable, of } from 'rxjs'; export class MyPreloadingStrategy implements PreloadingStrategy { preload(route: Route, fn: (a)= > Observable<any>): Observable<any> { return route.data && route.data.preload ? fn() : of(null); }}Copy the code
-
Inject into the service in the root module
import { MyPreloadingStrategy } from './common/my-preloading-strategy'; /* @NgModule takes a metadata object that tells Angular how to compile and launch the application */ @NgModule({ declarations: [AppComponent], // Import the components, directives, pipes that the current project is running imports: [BrowserModule, AppRoutingModule, HomeModule, UserModule], // Introduce the current module to run dependent on other modules exports: [], // It is exposed to the public providers: [MyPreloadingStrategy], // Define the service bootstrap: [AppComponent] // Specify the main view of the application }) export class AppModule {} Copy the code
-
4. Use it in the root route
@NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: MyPreloadingStrategy }) ], exports: [RouterModule] }) export class AppRoutingModule {} Copy the code
-
Ten, use,Location
The module returns to the previous menu
-
1, guide package
import { Location } from '@angular/common' Copy the code
-
2, use,
// Return to the upper-level menu private goback(): void { this.location.back(); } Copy the code