Angular 路由的参数传递

文中使用的工具或者包的版本:Angular CLI 11.0.6

文中 Demo 链接:https://stackblitz.com/edit/angular-route-params-xuspvu

一、路径参数

配置

{ path: 'route1/:id', component: Route1Component }

激活

<a [routerLink]="['/route1', 26]">route1</a>

或者:

this.router.navigate(['/route1', 26]);

URL

http://localhost:4200/route1/26

读取

const id = this.route.snapshot.params.id;

二、对象参数

配置

{ path: 'route2', component: Route2Component }

激活

<a [routerLink]="['/route2', { a: 1, b: 2 }]">route2</a>

或者:

this.router.navigate(['/route2', { a: 1, b: 2 }]);

URL

http://localhost:4200/route2;a=1;b=2

读取

const { a, b } = this.route.snapshot.params;

三、查询参数

配置

{ path: 'route3', component: Route3Component }

激活

<a [routerLink]="['/route3']" [queryParams]="{ a: 1, b: 2 }">route3</a>

或者:

this.router.navigate(['/route3'], { queryParams: { a: 1, b: 2 }});

URL

http://localhost:4200/route3?a=1&b=2

读取

const { a, b } = this.route.snapshot.queryParams;

四、data

配置

{ path: 'route4', component: Route4Component, data: { a: 1, b: 2 }}

读取

const { a, b } = this.route.snapshot.data;

五、resolve

配置

{ path: 'route5', component: Route5Component, resolve: { a: aResolver }}
@Injectable({ providedIn: 'root' })
export class aResolver {
  resolve() {
    return new Promise(res => {
        setTimeout(() => { res(1); }, 3000);
    });
  }
}

读取

const { a } = this.route.snapshot.data;

六、总结

  • 所有参数传递的方法可以一起使用;
  • 路径参数、对象参数、查询参数会在 URL 上体现,在路由激活时传参;
  • 配置 data 和 resolve 不影响 URL,在路由定义时传参;
  • 当 resolve 返回 promise 时,路由会等到异步任务完成后再激活;
posted @ 2021-04-18 22:39  文燚  阅读(639)  评论(0编辑  收藏  举报