【问题标题】:Pass objects during router navigate在路由器导航期间传递对象
【发布时间】:2022-02-23 06:14:20
【问题描述】:

我想在路由器导航到目标组件期间传递对象。 目前我正在使用 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


【解决方案1】:

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

您必须将服务注入构造函数,以便写入/读取您的对象参数

【讨论】:

  • 但是不要放在providers中(如果这样做会创建一个新对象,所有数据都会丢失)...您还可以使用 EventEmitter 传递/发送数据并在目标中订阅它.. .
  • 我已将 ElementDataService 包含在 main.ts 引导程序中。除了服务仅包含一个属性以及 getter 和 setter 方法。它目前对我有用。怎样才能做得更好?
【解决方案2】:

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

【讨论】:

    【解决方案3】:
    //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')
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2018-12-24
        • 2015-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-17
        • 2016-08-27
        • 1970-01-01
        • 2018-03-08
        相关资源
        最近更新 更多