Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass objects during router navigate

I would like to pass objects during router navigate to the target component. Currently I am using routeParams and I stringify my objects to strings. This approach works, but I don't like this solution. How would a better solution look like?

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();
        }
    }
} 
like image 589
Johannes Avatar asked Jan 23 '26 17:01

Johannes


2 Answers

//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')
like image 132
Rohit Sengar Avatar answered Jan 26 '26 12:01

Rohit Sengar


Another approach would be to store the temporary params in a Shared Service

You'd have to inject the service into constructors, in order to write/read your object params

like image 31
null canvas Avatar answered Jan 26 '26 11:01

null canvas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!