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();
}
}
}
//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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With