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

Joh*_*nes 2 typescript angular2-routing angular

我想在路由器导航到目标组件期间传递对象。目前我正在使用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();
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

Roh*_*gar 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')
Run Code Online (Sandbox Code Playgroud)