angular 路由功能很是強大,同時angular的路由也很是脆弱,很是容易出現錯誤。javascript
那麼在咱們遇到異常時,首先要作的是什麼?java
第一步:檢查代碼,對比官方文檔,發現代碼中不一致的地方進行改正。ide
第二步:調試代碼,觀察調用過程當中參數傳遞是否正常。學習
第三步:百度一下。this
對於我這個觀點,可能會有人不服氣,出現異常不該該第一時間問度娘嗎?對於較熟悉angular 路由的人來講,這確實是一個快速的解決問題之道,但不是咱們學習的根本。咱們學習要知根知底。url
對於angular的子路由,咱們來看一個例子spa
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { Leftlistzuhezuheleftlistform1030RootComponent } from './components/root-component/rootcomponent'; import { RootComponent as zuheRight2Form1030RootComponent } from '../../../../zuheright2form1030/components/root-component/rootcomponent'; const routes: Routes = [ { path: '', component: Leftlistzuhezuheleftlistform1030RootComponent, children: [{ path: 'KK/:id/:name' , component: zuheRight2Form1030RootComponent } ] } ]; @NgModule({ imports: [ RouterModule.forChild(routes) ], exports: [ RouterModule ] }) export class Leftlistzuhezuheleftlistform1030zuheleftListForm1030RoutingModule { }
咱們如何進行路由跳轉呢,咱們通常經過路由組件的navigate方法,而不是經過超連接,畢竟經過代碼能夠自定義變量、自定義url、自定義一系列東東。調試
import { Injectable } from '@angular/core'; import { Router, RouterModule, ActivatedRoute } from '@angular/router'; @Injectable() export class ZuheleftListForm1030FrmVfvfvfService { constructor( private router: Router, private route: ActivatedRoute) { } dk() { console.log("執行路由跳轉"); this.router.navigate(["right1"],{relativeTo:this.route}); } }
當咱們經過咱們自定義的方法進行路由跳轉時,咱們看到控制檯輸出了 執行路由跳轉字樣,說明這個方法被調用了,可是同時咱們在控制檯也看到了一個錯誤:Navigation triggered outside Angular zone, did you forget to call ‘ngZone.run() 。雖然該錯誤並無被標記成error但咱們仍要解決下,不然路由跳轉會出現讓咱們意想不到的結果。code
如何解決該問題呢?經過分析咱們代碼,咱們發現咱們自定義的方法並無包含在angular 的ngZone中,那麼什麼是ngZone呢。component
瞭解了一系列的緣由,解決該問題就比較簡單了,從ngZone中去執行路由跳轉,便可。
處理方式:
import { Injectable,NgZone } from '@angular/core'; import { Router, RouterModule, ActivatedRoute } from '@angular/router'; @Injectable() export class ZuheleftListForm1030FrmVfvfvfService { constructor( private router: Router, private route: ActivatedRoute, private ngZone: NgZone, ) { } dk() { console.log("執行路由跳轉"); this.ngZone.run(()=>{ this.router.navigate(["kk"],{relativeTo:this.route}).then(); }); } }
angular 路由跳轉常常出現找不到匹配Url的問題,針對這個問題,咱們首選的方案是將子路由相對當前路由進行跳轉。也就是咱們在執行
this.router.navigate(["kk"],{relativeTo:this.route}).then();
加上relativeTo的緣由。相對當前路由進行跳轉,能夠最大限度的減小路由地址不匹配的問題。angular 路由須要咱們持續的去審閱,多嘗試,多閱讀,必然瞭然於心。