首頁 > web前端 > js教程 > 主體

Angular4中路由Router類別的實例詳解

零下一度
發布: 2017-06-26 11:04:40
原創
1547 人瀏覽過

最近一直在學習angular4,它確實比以前有了很大的變化和改進,好多地方也不是那麼容易就能理解,好在官方的文檔和例子是中文,對英文不太好的還是有很大幫助去學習。

官方位址:

在學習的過程中路由(router)機制是離不開的,而且好多地方都要用到。

首先路由設定Route:

 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 {}
登入後複製
View Code

其次路由跳轉Router. navigate

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 : boolean10 }
登入後複製
View Code

1.以根路由跳轉/login

this.router.navigate(['login']);

2.設定relativeTo相對目前路由跳轉,route是ActivatedRoute的實例,使用需要匯入ActivatedRoute

this.router.navigate(['login', 1],{relativeTo: route}); 

3.路由中傳參數/login?name=1

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 }); 

 

還有好多好多東西要學習,關於跳轉就先寫到這裡了,希望大家共同學習分享踏過的坑。

 

以上是Angular4中路由Router類別的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!