Angular学习笔记2--路由

基本配置和使用

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

猜你喜欢

转载自blog.csdn.net/tj297202234/article/details/84032346