angular11源碼探索二十五[Router路由事件]

RouterEvent

觸發事件的條件: routerLink ,navigateByUrl() , navigate()

路由器整個經歷的事件經歷,而不是與特定路由相關的事件。對任何給定的導航觸發一次。

上官網給的小案例

class MyService {
  constructor(public router: Router, logger: Logger) {
    router.events.pipe(
       filter((e: Event): e is RouterEvent => e instanceof RouterEvent)
    ).subscribe((e: RouterEvent) => {
      logger.log(e.id, e.url);
    });
  }
}

我們發現默認刷新頁面有路由事件,刷新的是NavigationEnd

當導航開始時觸發的事件。

navigationTrigger

識別觸發導航的呼叫或事件。

* 'imperative'觸發器是對' router.navigateByUrl() '或' router.navigate() '的調用。
* popstate 的觸發器  Location.方法 跳轉
* hashchange 暫時沒發現使用方法
navigationTrigger?: 'imperative'|'popstate'|'hashchange';

restoredState

pushStatepopstate事件觸發導航時,先前提供給呼叫的導航狀態。否則爲null。

寫個案例你就懂了

<a [routerLink]="['a']" [state]="{foo: 'bar'}">aaa</a><br>
<a [routerLink]="['b']">bbb</a><br>
<a [routerLink]="['c']">ccc</a><br>
<a [routerLink]="['d']">ddd</a><br>
<bution (click)="clickMethod()">返回</button>
export class TwoComponent implements OnInit {

  constructor(
    private router:Router,
    private location:Location
  ) {
    this.router.events.pipe(
      filter((e:Event)=>(e instanceof NavigationStart))
    ).subscribe(res=>{
      console.log(res);
        // {id: 2, url: "/home/b", navigationTrigger: "imperative", restoredState: null}
    })
  }
 
  clickMethod() {
    this.location.back()
  }
}

當我們點擊返回的時候,相當於通過restoredState 拿到之前的路由狀態,類似滾動位置,state,hash,問好傳參等, 參數參考NavigationExtras

RoutesRecognized

​ 當路由被識別時觸發的事件

​ 由於意外錯誤導致導航失敗時觸發的事件。

當前路由 `/d`, 訪問一個不存在的路由,報錯信息,返回是當前的路由
export class TwoComponent implements OnInit {

  constructor(
    private router: Router,
    private location: Location
  ) {
    this.router.events.subscribe(e=>{
      if (e instanceof NavigationError) {
        console.log(e.url);
		// 跳轉報錯的Url  /home/dcccc
        console.log(router.url); 
          //  /d
        console.log(location.path());
          //  /d
      }
    }
}            
如果你想去掉控制檯的報錯信息,然後也不影響 NavigationError事件的正常的查詢
    this.router.navigate(['/home/dcccc']).catch(()=>null)                            

當導航被直接或間接取消時觸發的事件。

路由守衛返回false

export class TwoService implements CanActivate{
// 如果您有在導航過程中返回的路線保護false,您將獲得一個NavigationCancel事件。返回值是false,Promise解析爲false還是Observable發出都沒有關係false。最終結果將是相同的。
    canActivate() {
      // Case 1
      return false;

      // Case 2
      return Promise.resolve(false);

      // Case 3
      return new Observable<boolean>(observer => {
        observer.next(false);
        observer.complete();
      });
    }     
}
const routes: Routes = [{ path: '', component: TwoComponent,children:[
    {path:'a',component:AComponent},
    {path:'b',component:BComponent,
    canActivate:[TwoService]
    },
    {path:'c',component:CComponent},
  ] }];

export class TwoComponent implements OnInit {

  constructor(
    private router: Router,
    private location: Location
  ) {
    this.router.events.subscribe(e=>{
      if (e instanceof NavigationCancel) {
        console.log(e);// 當前要跳轉的事件信息
        console.log(location.path());
          //當前沒跳轉到的事件,加入當前是 /c 保存不變,路由守衛被攔截啦
      }
    })
  }
}    

當重定向也會觸發

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean {
//手動啓動一個新的導航和
//通過返回false取消當前的  
    this.router.navigateByUrl('/home/d')
    return false
//第二種方法
      //路由器將自動取消
	 //當前的導航並開始一個新的
    this.router.parseUrl('/home/d')      
  }
// NavigationCancel {id: 5, url: "/home/b", reason: "Navigation ID 5 is not equal to the current navigation id 6"}

導航路線

NavigationStart  
	當導航開始時觸發此事件
    觸發條件: popState(瀏覽器的前進/後退),navigateByUrl(),navigate()
	如果是popState觸發,那麼我們獲取前一個的狀態
	//如果跳轉的是懶加載的路由路徑
    RouteConfigLoadStart
        當延遲加載路由之前

    RouteConfigLoadEnd
        當延遲加載路由之後

RoutesRecognized
	當路由被識別時觸發的事件。

GuardsCheckStart
	路由守衛階段開始
    
ChildActivationStart
	路由解析階段的子孩子激活部分開始
    
ActivationStart
	路由激活部分開始時觸發
    
GuardsCheckEnd
	路由守衛階段結束時
    
ResolveStart
	解決延遲守衛階段開始
    
ResolveEnd
	解決延遲守衛結束
    
ActivationEnd
	路由激活部分結束時觸發

ChildActivationEnd
	路由解析階段的子孩子激活結束時

Scroll
	由滾動觸發的事件
    
NavigationEnd
	導航成功結束時觸發的事件
    
    NavigationCancel
        當導航被直接或間接取消時觸發的事件。

    NavigationError
        由於意外錯誤導致導航失敗時觸發的事件。

在懶加載中出來加載過長

可以通過懶加載的路由事件去修改

this.router.events.subscribe(event => {
    if (event instanceof RouteConfigLoadStart) {
 	   this.isRouteLoading = true;
    } else if (event instanceof RouteConfigLoadEnd) {
 	   this.isRouteLoading = false;
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章