通過路由導航傳遞參數
this.router.navigateByUrl('/user', { state: { orderId: 1234 } });
<a [routerLink]="/user" [state]="{ orderId: 1234 }">Go to user's detail</a>
狀態將保留在瀏覽器的hostory.state屬性上
在跳轉到的頁面上
export class DyTwoComponent implements OnInit {
constructor(private router:Router) {
console.log(this.router.getCurrentNavigation().extras.state);
}
ngOnInit(): void {
console.log(history.state);
}
}
注意一個坑, 當你使用
getCurrentNaviagation
的時候,你需要在constructor
中進行調用,不然調用不到,或者在ngOnInit
直接拿也可以
記錄快照
我們從
/ccc/1
導航到/ccc/123
需要記錄當前數據變化
export class DyTwoComponent implements OnInit {
constructor(private r:ActivatedRoute) {
r.url.subscribe((val)=>{
console.log(val);
})
}
}
Navigation修改導航策略
可以理解成vue里面的編程式導航
相對導航
{
path: 'two/:id',
component: DyTwoComponent,
children:[
{
path:'one',
component:DyOneComponent
},
{
path: 'ref',
component: RefsComponent,
}
]
}
假設當前路由是 /two
<div (click)="clickDown('one')">跳one子路由</div>
<div (click)="clickDown('ref')">跳ref子路由</div>
export class DyTwoComponent implements OnInit {
constructor(private router: Router, private r: ActivatedRoute) { }
ngOnInit(): void {}
clickDown(item: string) {
this.router.navigate(['./' + item], {relativeTo: this.r})
'../' //那么會跳轉到 /one /ref 前面沒有two
}
}
跳轉到 two/one
跳轉到 two/ref
但是當 two/:id 是動態的跳轉會報錯,暫時不知道怎么解決
加問號參數
/results?page=1
this.router.navigate(['/results'], { queryParams: { page: 1 } });
設置URL的哈希片段
/results#top
this.router.navigate(['/results'], { fragment: 'top' });
參數合並
/results?page=1 to /view?page=1&page=2
this.router.navigate(['/view'], { queryParams: { page: 2 }, queryParamsHandling: "merge" });
保留URL片段用於下一次導航
/results#top /view#top
this.router.navigate(['/view'], { preserveFragment: true });
不會記錄到歷史記錄
this.router.navigate(['/view'], { skipLocationChange: true });
替換當前的歷史記錄
this.router.navigate(['/view'], { replaceUrl: true });
重新刷新路由
/pro/1 切換到/pro/1221
clickDown() {
this.router.navigateByUrl('/pro/1221');
this.router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
};
}
我們發現生命周期會重新執行
Route
定義單個路由的配置對象
通配符
無論你導航到何處,來執行實例化的組件
[{ path: '**', component: WildcardComponent }]
重定向
redirectTo
空路徑
空路徑會繼承父級的參數和數據
/team/12 實例化的是
AllUsers
組件[{ path: 'team/:id', component: Team, children: [{ path: '', component: AllUsers }, { path: 'user/:name', component: User }] }]
匹配策略
前綴匹配
/team/12/user /team/:id 匹配
{
path: '',
pathMatch: 'prefix', //default
redirectTo: 'main'
}
pathMatch: 'full', 完整匹配
{ path: '', redirectTo: 'list', pathMatch: 'full' },
路由守衛
觸發順序:
canload 加載
canActivate 進入(重要)
canActivateChild 進入子路由
canDeactivate 離開(重要)
我只能簡要的實現以下
創建一個服務
import {Injectable} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
CanDeactivate,
Router,
RouterStateSnapshot
} from "@angular/router";
import {DyOneComponent} from "./dy-one/dy-one.component";
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate, CanDeactivate<DyOneComponent> {
constructor(private router: Router) {
}
// 進入
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const url: string = state.url;
console.log(url);
return true;
}
// 離開
canDeactivate(component:DyOneComponent,currentRoute:ActivatedRouteSnapshot,currentState:RouterStateSnapshot) {
return window.confirm('是否離開這個模塊')
}
}
DyOneComponent 是你離開這個頁面所在的組件
路由
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuardService],// 進入
canDeactivate:[AuthGuardService] // 離開
}
是否需要恢復之前滾動的位置ExtraOptions
@NgModule({
imports: [RouterModule.forRoot(routes,{ scrollPositionRestoration: 'enabled',})],
exports: [RouterModule]
})
自定義滾動記錄
constructor(private router: Router, private viewportScroller: ViewportScroller) {
this.router.events.pipe(
filter((e: Scroll) => e instanceof Scroll)
).subscribe(
e => {
if (e.position) {
// 后退
viewportScroller.scrollToPosition(e.position);
} else if (e.anchor) {
// 哈希
viewportScroller.scrollToAnchor(e.anchor);
} else {
// forward navigation
viewportScroller.scrollToPosition([0, 0]);
}
}
)
}
resolve
resolve 保證了數據獲取后在進行路由跳轉,防止因為數據延遲而出現的空組件情況
也可以應用resolve 來進行路由攔截
總是寫着有問題,沒辦法只要有一個不是很嚴謹的寫法
路由
{
path: 'two/:id',
component: TwoComponent,
resolve: {
detail: BlockService // 這個是攔截的路由
}
},
服務
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot} from "@angular/router";
import {Observable} from "rxjs";
import {map} from "rxjs/operators";
@Injectable()
export class BlockService implements Resolve<any> {
constructor(private router: Router) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
let ids = route.paramMap.get('id');
return new Observable(subscriber => {
subscriber.next(11)
}).pipe(
map(res => {
if (res == ids) { //成功
return res
} else {// 失敗
this.router.navigate(['/three']);
return false
}
})
).subscribe(val => {
return val
})
}
}
成功后才會展示那個組件
記得好好想想取消訂閱, 我看官網上說不需要取消訂閱,具體點還需要探究