Angular4中路由Router類中navigate跳轉(zhuǎn)用法
之前通過學(xué)習(xí) angular4 框架的開發(fā),它確實比以前有了很大的變化和改進,好多地方也不是那么容易就能理解,好在官方的文檔和例子是中文,示例相對簡單,對英文不太好的伙伴們學(xué)習(xí)還是有很大幫助。

官方地址:https://angular.cn/
路由文檔:https://angular.cn/api/router/router#instance-methods
在學(xué)習(xí)的過程中首先要學(xué)習(xí)掌握框架的基礎(chǔ)知識,接著就是路由(router)機制的學(xué)習(xí),項目開發(fā)中路由是離不開的,且好多地方都要用到。
路由配置(Route)
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home.component'; import { LoginComponent } from './login.component'; import { RegisterComponent } from './register.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: 'heroes', component: RegisterComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {}
路由跳轉(zhuǎn)(Router.navigate)
navigate(commands: any[], extras?: NavigationExtras) : Promise
interface NavigationExtras { relativeTo : ActivatedRoute queryParams : Params fragment : string preserveQueryParams : boolean queryParamsHandling : QueryParamsHandling preserveFragment : boolean skipLocationChange : boolean replaceUrl : boolean }
其它屬性和方法
根路由跳轉(zhuǎn)(/login)
this.router.navigate(['login']);
設(shè)置relativeTo相對當前路由跳轉(zhuǎn),route是ActivatedRoute的實例,使用需要導(dǎo)入ActivatedRoute
this.router.navigate(['login', 1],{relativeTo: route});
路由中傳參數(shù)(/login?name=1)
this.router.navigate(['login', 1],{ queryParams: { name: 1 } });
保留之前路由中的查詢參數(shù),將 preserveQueryParams 默認值為false,設(shè)為true,如(/login?name=1 to /home?name=1)
this.router.navigate(['home'], { preserveQueryParams: true });
路由中錨點跳轉(zhuǎn)(/home#top)
this.router.navigate(['home'],{ fragment: 'top' });
保留之前路由中的錨點,將 preserveFragment 默認為false,設(shè)為true,如(/home#top to /role#top)
this.router.navigate(['/role'], { preserveFragment: true });
路由跳轉(zhuǎn)時瀏覽器中的url會保持不變,但是傳入的參數(shù)依然有效,將 skipLocationChange 默認為false,設(shè)為true
this.router.navigate(['/home'], { skipLocationChange: true });
路由不進行跳轉(zhuǎn),將 replaceUrl 默認為true,設(shè)為false
this.router.navigate(['/home'], { replaceUrl: true });
溫馨提示
文章內(nèi)容如果寫的存在問題歡迎留言指出,讓我們共同交流,共同探討,共同進步~~~
文章如果對你有幫助,動動你的小手點個贊,鼓勵一下,給我前行的動力。
Angular JavaScript
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔相應(yīng)法律責任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔相應(yīng)法律責任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實的內(nèi)容,請聯(lián)系我們jiasou666@gmail.com 處理,核實后本網(wǎng)站將在24小時內(nèi)刪除侵權(quán)內(nèi)容。