美文网首页
angular路由传参的三种姿势

angular路由传参的三种姿势

作者: myzony | 来源:发表于2019-05-23 16:20 被阅读0次

    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 初始化调用
        }
    }
    

    相关文章

      网友评论

          本文标题:angular路由传参的三种姿势

          本文链接:https://www.haomeiwen.com/subject/qsdbzqtx.html