詳解Angular4中路由Router類的跳轉navigate,angular4navigate

來源:互聯網
上載者:User

詳解Angular4中路由Router類的跳轉navigate,angular4navigate

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

官方地址:https://angular.cn/docs/ts/latest/api/router/index/Router-class.html

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

首先路由配置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 {}

 其次路由跳轉Router.navigate

 navigate(commands: any[], extras?: NavigationExtras) : Promise<boolean>
 interface NavigationExtras {  relativeTo : ActivatedRoute  queryParams : Params  fragment : string  preserveQueryParams : boolean  queryParamsHandling : QueryParamsHandling  preserveFragment : boolean  skipLocationChange : boolean  replaceUrl : boolean}

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

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.