一、路由的基本使用
- 1、建立兩個元件
ng g c components/home ng g c components/news
- 2、在
中配置路由app-routing.module.ts
const routes: Routes = [ // 預設通路位址 { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'news', component: NewsComponent }, // 當沒有比對的時候就到home路由 { path: '**', redirectTo: 'home', pathMatch: 'full' } ];
- 3、使用路由跳轉
<ul> <li> <a routerLink="home">首頁</a> </li> <li> <a routerLink="news">新聞</a> </li> </ul> <!-- 路由切換的槽 --> <router-outlet></router-outlet>
二、幾種路由跳轉的方式
- 1、方式一直接使用
- 2、動态傳遞值的方式
三、路由選中的樣式
四、動态路由
- 1、配置路由檔案
... { path: 'news', component: NewsComponent }, { path: 'news/:id', component: DetailComponent }, ...
- 2、配置路由的跳轉
<ul> <li *ngFor="let item of articleList"> <a [routerLink]="['/news', item.id]">{{item.title}}</a> <!-- <a routerLink="/news/{{item.id}}">跳轉到詳情</a> --> </li> </ul>
- 3、擷取動态路由傳遞過來的值
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); }); // 或者使用snapshot是路由的一個快照【id為你寫的動态路由的】 console.log(this.route.snapshot.paramMap.get('id')); } ngOnDestroy() { this.sub.unsubscribe(); } }
五、使用 query
傳遞參數
query
- 1、路由跳轉的時候
<a [routerLink]="['news']" [queryParams]="{ id: 1, name: 'hello', age: 20 }" routerLinkActive="active" >新聞</a >
- 2、元件中擷取路由參數
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(); } }
六、在 js
中路由跳轉
js
- 1、不帶參數的跳轉
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']); } }
- 2、帶參數的跳轉(動态路由的方式)
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']); } }
- 3、帶
參數的跳轉query
import { ActivatedRoute, Router, NavigationExtras } from '@angular/router'; ... public goHome() { const navigationExtras: NavigationExtras = { // query參數 queryParams: { name: 'hello', age: 20 }, fragment: 'aaa' // 錨點 }; this.router.navigate(['/home'], navigationExtras); }
七、路由的嵌套
- 1、配置路由
const routes: Routes = [ { path: 'home', component: HomeComponent, children: [ { path: 'add', component: AddComponent }, { path: 'edit', component: EditComponent } ] }, ... ]
- 2、配置路由的跳轉
<p> <a [routerLink]="['/home/add']" routerLinkActive="active">添加内容</a> </p> <p> <a [routerLink]="['/home/edit']" routerLinkActive="active">編輯内容</a> </p>
八、路由與懶加載子產品
- 1、建立兩個
和對應的元件module
ng g m pages/home --routing # 建立帶路由的子產品 ng g m pages/user --routing # 建立元件 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
- 2、主路由
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' } ];
- 2、
的路由home
const routes: Routes = [ { path: '', redirectTo: 'index', pathMatch: 'full' }, { path: 'index', component: HomeComponent }, { path: '**', redirectTo: 'index', pathMatch: 'full' } ];
- 3、使用者的路由
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' } ];
九、子產品的預加載
上面對子產品進行了懶加載,那麼進入頁面後不會全部加載出來,需要使用者點選當頁面後才會加載目前的資料,但是這樣往往有個弊端(有些資料一開始是沒有的,需要等待下才會出現)。為了解決這個等待,我們可以進行預加載
- 1、方式一、簡單粗暴的方法(直接在根路由下使用
預設是PreloadAllModules
)NoPreloading
import { Routes, RouterModule, PreloadAllModules } from '@angular/router'; @NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], exports: [RouterModule] }) export class AppRoutingModule {}
- 2、方式二、根據自己配置去預加載對應的子產品
- 配置自己需要預加載的路由
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 } } ];
- 自己建立一個
my-preloading-strategy.ts
import { Route, PreloadingStrategy } from '@angular/router'; import { Observable, of } from 'rxjs'; export class MyPreloadingStrategy implements PreloadingStrategy { preload(route: Route, fn: () => Observable<any>): Observable<any> { return route.data && route.data.preload ? fn() : of(null); } }
- 3、在根子產品中注入服務中
import { MyPreloadingStrategy } from './common/my-preloading-strategy'; /* @NgModule接受一個中繼資料對象,告訴angular如何編譯和啟動應用 */ @NgModule({ declarations: [AppComponent], // 引入目前項目運作的元件、指令、管道 imports: [BrowserModule, AppRoutingModule, HomeModule, UserModule], // 引入目前子產品運作依賴别的子產品 exports: [], // 對外暴露出去的 providers: [MyPreloadingStrategy], // 定義的服務 bootstrap: [AppComponent] // 指定應用的主視圖 }) export class AppModule {}
- 4、在根路由中使用
@NgModule({ imports: [ RouterModule.forRoot(routes, { preloadingStrategy: MyPreloadingStrategy }) ], exports: [RouterModule] }) export class AppRoutingModule {}
- 配置自己需要預加載的路由
十、使用 Location
子產品傳回到上一個菜單
Location
- 1、導包
import { Location } from '@angular/common'
- 2、使用
// 傳回上一級菜單 private goback(): void { this.location.back(); }