Angular9 訪問查詢參數(shù)與片段

2020-07-07 13:37 更新

有時,應用中的某個特性需要訪問路由的部件,比如查詢參數(shù)或片段(fragment)。本教程的這個階段使用了一個“英雄指南”中的列表視圖,你可以在其中點擊一個英雄來查看詳情。路由器使用 id 來顯示正確的英雄的詳情。

首先,在要導航的組件中導入以下成員。

  1. //Component import statements (excerpt)
  2. import { ActivatedRoute } from '@angular/router';
  3. import { Observable } from 'rxjs';
  4. import { switchMap } from 'rxjs/operators';

接下來,注入當前路由(ActivatedRoute)服務:

  1. //Component (excerpt)
  2. constructor(private route: ActivatedRoute) {}

配置這個類,讓你有一個可觀察對象 heroes$、一個用來保存英雄的 id 號的 selectedId,以及 ngOnInit() 中的英雄們,添加下面的代碼來獲取所選英雄的 id。這個代碼片段假設你有一個英雄列表、一個英雄服務、一個能獲取你的英雄的函數(shù),以及用來渲染你的列表和細節(jié)的 HTML,就像在《英雄指南》例子中一樣。

  1. //Component 1 (excerpt)
  2. heroes$: Observable;
  3. selectedId: number;
  4. heroes = HEROES;
  5. ngOnInit() {
  6. this.heroes$ = this.route.paramMap.pipe(
  7. switchMap(params => {
  8. this.selectedId = Number(params.get('id'));
  9. return this.service.getHeroes();
  10. })
  11. );
  12. }

接下來,在要導航到的組件中,導入以下成員。

  1. //Component 2 (excerpt)
  2. import { Router, ActivatedRoute, ParamMap } from '@angular/router';
  3. import { Observable } from 'rxjs';

在組件類的構造函數(shù)中注入 ActivatedRouteRouter,這樣在這個組件中就可以用它們了:

  1. //Component 2 (excerpt)
  2. item$: Observable;
  3. constructor(
  4. private route: ActivatedRoute,
  5. private router: Router ) {}
  6. ngOnInit() {
  7. let id = this.route.snapshot.paramMap.get('id');
  8. this.hero$ = this.service.getHero(id);
  9. }
  10. gotoItems(item: Item) {
  11. let heroId = item ? hero.id : null;
  12. // Pass along the item id if available
  13. // so that the HeroList component can select that item.
  14. this.router.navigate(['/heroes', { id: itemId }]);
  15. }

惰性加載

你可以配置路由定義來實現(xiàn)惰性加載模塊,這意味著 Angular 只會在需要時才加載這些模塊,而不是在應用啟動時就加載全部。 另外,你可以在后臺預加載一些應用部件來改善用戶體驗。

關于惰性加載和預加載的詳情,請參見專門的指南惰性加載 NgModule。

防止未經授權的訪問

使用路由守衛(wèi)來防止用戶未經授權就導航到應用的某些部分。Angular 中提供了以下路由守衛(wèi):

  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • Resolve
  • CanLoad

要想使用路由守衛(wèi),可以考慮使用無組件路由,因為這對于保護子路由很方便。

為你的守衛(wèi)創(chuàng)建一項服務:

  1. ng generate guard your-guard

請在守衛(wèi)類里實現(xiàn)你要用到的守衛(wèi)。下面的例子使用 CanActivate 來保護該路由。

  1. //Component (excerpt)
  2. export class YourGuard implements CanActivate {
  3. canActivate(
  4. next: ActivatedRouteSnapshot,
  5. state: RouterStateSnapshot): boolean {
  6. // your logic goes here
  7. }
  8. }

在路由模塊中,在 routes 配置中使用相應的屬性。這里的 canActivate 會告訴路由器它要協(xié)調到這個特定路由的導航。

  1. //Routing module (excerpt)
  2. {
  3. path: '/your-path',
  4. component: YourComponent,
  5. canActivate: [YourGuard],
  6. }
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號