這篇文章給大家比較一下Angular路由中navigateByUrl和navigate,看看他們的不同點和共同點,希望對大家有幫助!
import { Router, ActivatedRoute } from '@angular/router'; export class xxx{ constructor(private router: Router, private route: ActivatedRoute){} }
【相關教學推薦:《angular教學》 】
navigateByUrl(url: string | UrlTree, extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
第一個參數必須是==絕對路徑==的字串。
this.router.navigateByUrl('/home');
他兩個接收的第一個參數不同,第二個參數相同。
navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
第一個參數是一個陣列
this.router.navigate(['home', 'demo'])
那麼解析的路由就是localhost:4200/home/demo
。
可以相對目前路由進行導航
傳入一個relativeTo
參數,即可相對傳入的路由進行跳轉。如目前在localhost:4200/home
,
this.router.navigate(['demo'], {relativeTo: this.route})
跳轉後的位址為localhost:4200/home/demo
。
但如果'demo'
寫成'/demo'
傳入的路由就不起作用了,會以根路由進行導航。如果不傳入也是預設以根路由(localhost:4200)進行導航。
interface NavigationExtras { relativeTo?: ActivatedRoute | null queryParams?: Params | null fragment?: string preserveQueryParams?: boolean queryParamsHandling?: QueryParamsHandling | null preserveFragment?: boolean skipLocationChange?: boolean replaceUrl?: boolean state?: {...} }
##以navigate 舉例#透過queryParams傳參此種傳參方式會將參數拼接在url上,如
localhost:4200/demo?id=1
A元件傳遞參數
this.router.navigate(['demo'], {queryParams: {id: 1} , relativeTo: this.route})
B元件接收參數
方式傳遞過來用
activatedRoute.params
import { ActivatedRoute } from '@angular/router'; constructor(private activatedRoute: ActivatedRoute) { this.activatedRoute.params.subscribe((param) => { console.log('组件里面的param', param);// {id :1} }); }
方式傳遞用
activatedRoute.queryParams
import { ActivatedRoute } from '@angular/router'; constructor(private activatedRoute: ActivatedRoute) { this.activatedRoute.queryParams.subscribe((param) => { console.log('组件里面的queryParams', param); // {id :1} }); }
A元件傳遞參數
import { Component, Input } from '@angular/core'; import { Router, NavigationExtras } from '@angular/router'; @Component({ selector: 'a-component', template: ` <button (click)="test()">Test</button> `, }) export class AComponent { constructor(private router: Router){} test(){ const navigationExtras: NavigationExtras = {state: {id: 1}}; this.router.navigate(['b'], navigationExtras); } }
B元件接收參數
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'b-component' }) export class BComponent { constructor(private router: Router) { const navigation = this.router.getCurrentNavigation(); const state = navigation.extras.state as {id: number}; // state.id 就是传过来的数据 } }
this.router.navigate(['demo']).then(nav => { console.log(nav); // true: 跳转成功, false 跳转失败 }, err => { console.log(err) // 发生无措 });
更多用法更新於 github:https://github.com/deepthan/blog-angular更多程式相關知識,請造訪:
程式設計入門! !
以上是淺析Angular路由中navigateByUrl和navigate的區別和共同點的詳細內容。更多資訊請關注PHP中文網其他相關文章!