最近一直在學習angular4,它確實比之前有了很大的變化和改進,好多地方也不是那麼容易就能理解,好在官方的文檔和例子是中文,對英文不太好的仍是有很大幫助去學習。html
官方地址:https://angular.cn/docs/ts/latest/api/router/index/Router-class.htmlapi
在學習的過程當中路由(router)機制是離不開的,而且好多地方都要用到。瀏覽器
首先路由配置Route:angular4
1 import { NgModule } from '@angular/core'; 2 import { RouterModule, Routes } from '@angular/router'; 3 4 import { HomeComponent } from './home.component'; 5 import { LoginComponent } from './login.component'; 6 import { RegisterComponent } from './register.component'; 7 8 const routes: Routes = [ 9 { path: '', redirectTo: '/home', pathMatch: 'full' }, 10 { path: 'home', component: HomeComponent }, 11 { path: 'login', component: LoginComponent }, 12 { path: 'heroes', component: RegisterComponent } 13 ]; 14 15 @NgModule({ 16 imports: [ RouterModule.forRoot(routes) ], 17 exports: [ RouterModule ] 18 }) 19 export class AppRoutingModule {}
其次路由跳轉Router.navigateide
1 navigate(commands: any[], extras?: NavigationExtras) : Promise<boolean>
1 interface NavigationExtras { 2 relativeTo : ActivatedRoute 3 queryParams : Params 4 fragment : string 5 preserveQueryParams : boolean 6 queryParamsHandling : QueryParamsHandling 7 preserveFragment : boolean 8 skipLocationChange : boolean 9 replaceUrl : boolean 10 }
1.以根路由跳轉/login學習
this.router.navigate(['login']);this
2.設置relativeTo相對當前路由跳轉,route是ActivatedRoute的實例,使用須要導入ActivatedRouteurl
this.router.navigate(['login', 1],{relativeTo: route});
spa
3.路由中傳參數 /login?name=1code
this.router.navigate(['login', 1],{ queryParams: { name: 1 } });
4.preserveQueryParams默認值爲false,設爲true,保留以前路由中的查詢參數/login?name=1 to /home?name=1
this.router.navigate(['home'], { preserveQueryParams: true });
5.路由中錨點跳轉 /home#top
this.router.navigate(['home'],{ fragment: 'top' });
6.preserveFragment默認爲false,設爲true,保留以前路由中的錨點/home#top to /role#top
this.router.navigate(['/role'], { preserveFragment: true });
7.skipLocationChange默認爲false,設爲true,路由跳轉時瀏覽器中的url會保持不變,可是傳入的參數依然有效
this.router.navigate(['/home'], { skipLocationChange: true });
8.replaceUrl默認爲true,設爲false,路由不會進行跳轉
this.router.navigate(['/home'], { replaceUrl: true });
還有好多好多東西須要學習,關於跳轉就先寫到這裏了,但願你們共同窗習分享踏過的坑。