angular路由传参的三种姿势

1、第一种(一般都采用这种姿势)

1、连接配置 queryParams

<a routerLink="/stock" [queryParams]="{id: 1}"></a>

2、ts

export class StockComponent implements OnInit {
    private stockId: number;
    constructor(private routeInfo: ActivatedRoute) {}
    ngOnInit() {
        this.stockId = this.routeInfo.snapshot.queryParams["id"]  // = 1
    }
}

2、第二种

1、路由配置

{ path: 'stock/:id', component: StockConponent }

2、连接配置

<a [routerLink]="['/stock', 1]"></a>

3、ts

export class StockComponent implements OnInit {
    private stockId: number;
    constructor(private routeInfo: ActivatedRoute) {}
    ngOnInit() {
        this.stockId = this.routeInfo.snapshot.params["id"]  // = 1
    }
}

3、第三种

1、路由配置

{ path: 'stock/:id', component: StockConponent, data: [{id: 2}] }

2、ts

export class StockComponent implements OnInit {
    private stockId: number;
    constructor(private routeInfo: ActivatedRoute) {}
    ngOnInit() {
        this.stockId = this.routeInfo.snapshot.data[0]["id"]  // = 1
    }
}

补充-事件跳转姿势

// 不带参数
this.router.navigateByUrl('/childAccount/add-account');
// 带参数
this.router.navigate(['/product/project/add'], { queryParams: {oper: 'edit'}});

补充-参数订阅问题

由于路由发生变化只会加载一次组件导致

import { ActivatedRoute, Params } from '@angular/router';
export class StockComponent implements OnInit {
    private stockId: number;
    constructor(private routeInfo: ActivatedRoute) {}
    ngOnInit() {
        this.routeInfo.params.subscribe((params: Params) => this.stockId = params['id']) // 每次参数发生变化都会被调用
        this.stockId = this.routeInfo.snapshot.params["id"]  // = 1 初始化调用
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。