在路由器导航期间传递对象

问题描述 投票:0回答:5

我想在路由器导航期间传递对象到目标组件。 目前我正在使用routeParams 并将我的对象字符串化为字符串。这种方法有效,但我不喜欢这种解决方案。更好的解决方案是什么样的?

export class Overview {
    //import {Router} from "@angular/router-deprecated";
    constructor(private router:Router) {}
    goToElementComponent(elem:Element) {
        this.router.navigate(['ElementDetail', {elem: JSON.stringify(elem)}]);
    }
}
export class ElementDetail {
    // import {RouteParams, Router} from "@angular/router-deprecated";
    this.elem : Element;

    constructor(private routeParams:RouteParams) {}

    ngOnInit() {
        var elem = JSON.parse(this.routeParams.get("elem"));
        if (elem) {
          this.elem = elem;
        } else {
          this.elem = new Element();
        }
    }
} 
typescript angular angular2-routing
5个回答
7
投票
//Note: router:Router and route:ActivatedRoute
//send object from one component (its independent parent-child relationship with //another component): 
  bill = {
    'customerName': "RAJESH",
    'billNo': "A230",
    'date': "23/12/2020",
    'address': "AGRA",
    'itemDetails':"HUSQVANA VITIPILEN",
    'grandTotal': 2500000
  }
this.router.navigate(['/billingpdf',{billing:JSON.stringify(this.bill)}])

//accessing this object into another component like this:
//-------------------------------------------------------
this.route.snapshot.paramMap.get('billing') //store this variable if you want use further
                                    or
this.route.snapshot.paramMap.getAll('billing')

3
投票

另一种方法是将临时参数存储在共享服务中

您必须将服务注入到构造函数中,才能写入/读取对象参数


0
投票

您可以使用导航方法的 NavigationExtras 参数来完成此操作。 NavigationExtras 对象应该具有状态参数,您可以在其中放置自定义数据:

this.router.navigate(['/route-to'], {
      state: {
        someData: { name: 'Some name', description: 'Some description' },
      },
    });

在目标组件中,我们以这种方式接收数据:

constructor(private router: Router) {
 this.dataFromRoute = this.router.getCurrentNavigation().extras.state?.['someData'];
}

-1
投票

在 queryParams 中传递对象,如下所示:

this.router.navigate(['/my-route'], {queryParams: myObject});

-3
投票

参见 http://ngcourse.rangle.io/handout/routing/routedata.html 有解决方法可以在 javascript 中执行此操作

© www.soinside.com 2019 - 2024. All rights reserved.