Angular學習筆記2--路由
阿新 • • 發佈:2018-12-21
基本配置和使用
const routes: Routes = [ // 基本配置 { path: "index", component: IndexComponent }, // 子路由 { path: "user", component: UserComponent, children: [ { path: "info", component: InfoComponent }, { path: 'settings', component: SettingsComponent } ]}, // 重定向 { path: "", redirectTo: '/index', pathMatch: 'full' }, // 萬用字元,其他路由失敗的,會跳轉到這個檢視 { path: '**', component: EmptyComponent } ];
路由跳轉及資料傳遞
路由跳轉
<a [routerLink]="['/']">跳轉到主頁</a>
<a [routerLink]="['./settings']">跳轉到設定頁</a>
<button (click)="skipToUser()" >跳轉到使用者頁面</button>
constructor(private route: Router) { }
skipToUser() {
this.route.navigateByUrl("user")
}
路由資料傳遞
在查詢引數中傳遞資料
<a [routerLink]="['/user']" [queryParams]="{id:1}">跳轉到使用者頁</a> constructor(private route: ActivatedRoute) { } ngOnInit() { console.log(this.route.snapshot.queryParams["id"]); }
在路由路徑中傳遞資料
<a [routerLink]="['/user', 1]">跳轉到使用者頁</a>
// 路由配置
{ path: "user/:id", component: UserComponent }
constructor(private route: ActivatedRoute) { }
ngOnInit() {
console.log(this.route.snapshot.params["id"]);
}
在路由配置中傳遞資料
<a [routerLink]="['/user']">跳轉到使用者頁</a> { path: "user", component: UserComponent, data:[{id:2}] } ngOnInit() { console.log(this.route.snapshot.data[0]["id"]); }
ts中跳轉
<button (click)="skipToUser()">跳轉到使用者頁</button>
constructor(private route: Router) { }
skipToUser() {
this.route.navigate(['/user', 5], { queryParams: { id: 10 }});
}
{ path: "user/:id", component: UserComponent }
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// console.log(this.route.snapshot.params["id"]);
// console.log(this.route.snapshot.queryParams["id"]);
this.route.params.subscribe((params: Params) => {
console.log(params["id"])
})
}
輔助路由(多頁面公用聊天視窗)
<router-outlet name="aux"></router-outlet>
{ path:'chat', component:ChatComponent, outlet:'aux' },
<a [routerLink]="[{outlets:{aux:'chat'}}]">開始聊天</a>
// 不顯示
<a [routerLink]="[{outlets:{aux:null}}]">結束聊天</a>
// 同時跳轉到home頁面
<a [routerLink]="[{outlets:{primary:home, aux:'chat'}}]">開始聊天</a>
路由守衛
鉤子函式
CanActivate: 處理導航到某路由的情況 CanDeactivate: 處理從當前路由離開的情況 Resolve: 在路由啟用之前獲取路由資料
當用戶已經登入並擁有某些許可權時才可以進入某些路由
1.實現CanActivate介面,返回boolean型別引數
export class Guard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean {
return undefined;
}
}
2.配置路由引數
{ path: "index", component: IndexComponent, canActivate: [Guard] }
3.注入物件
@NgModule({
providers: [Guard]
})
當用戶未執行儲存操作試圖離開當前頁面,給使用者提醒
實現CanDeactivate介面,注意泛型引數的傳入,其他同上
export class UnsaveGuard implements CanDeactivate<IndexComponent> {
canDeactivate(component: IndexComponent) {
return window.confirm("還沒有儲存,確定要離開嗎");
}
}
當進入一個也面前,提前請求好資料,攜帶引數進入頁面
1.實現Resolve介面,注意泛型的傳入
export class UserResolve implements Resolve<User> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<User>|Promise<User>|User {
return new User('123', '張三');
}
2.定義model類
export class User {
constructor(public id: string, public name: string) {}
}
3.路由配置和注入物件同上 4.資料接收
constructor(private route: ActivatedRoute) { }
public userId: string;
public userName: string;
ngOnInit() {
this.route.data.subscribe((data: [User]) => {
this.userId = data[0].id;
this.userName = data[0].name;
})
}