zoukankan      html  css  js  c++  java
  • 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 时,路由会等到异步任务完成后再激活;
  • 相关阅读:
    用内联取代宏代码
    参数的缺省值
    令人迷惑的隐藏规则
    重载与覆盖
    重载是如何实现的?
    重载的起源
    C++函数的高级特性
    使用调试器逐步跟踪程序
    new/delete 的使用要点
    malloc/free 的使用要点
  • 原文地址:https://www.cnblogs.com/yshenhua/p/14674955.html
Copyright © 2011-2022 走看看