Home > other >  How to read a param value correct
How to read a param value correct

Time:09-13

I'm trying to send an object from one page to the rerouted page using angular. I have found similar topics around this which I have tried to reproduce but I still get undefined value. Although I seem to do it right according to this topics.

  goToOrderPage(){

 //code to create object

    let order = new Order("BTWNummer", "mail", this.totalPrice, this.sendCosts, orderlineset)

    console.log(
      "before send"   
      order.btw   " - "   order.totalPrice   " - "   order.shippingcost   " - "   order.email
      );

      this.router.navigate(["/orderinfo"], { queryParams:  order });
  }

the object logs well and I have no error sending it. I get rerouted to the next page "/orderinfo":

export class OrderinfoComponent implements OnInit {
  order!:Order;

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.queryParams.subscribe(params=> {
      console.log(params);
      this.order = params['order'];
    
      console.log(
        this.order.btw   " - "   this.order.totalPrice   " - "   this.order.shippingcost   " - "   this.order.email
        );
    })
  }

}

Here do get an undefined value whilst logging the code. The console.log giving the queryparam does clearly log {order: Object object} I tried some other things to besides the code written down here, but I cannot get the value parsed. How do I properly parse to param value in the order object?

CodePudding user response:

You cannot just pass an entire object as a query parameter. You need to encode it somehow, because query string parameters are represented as... strings. You can either send every order property as a separate query string parameter, or look into other, more ergonomic ways of achieving the desired result. For example you can use navigation extras state

this.router.navigate(["/orderinfo"], { state: order });

Then in your OrderinfoComponent you can access it before the navigation ends (usually in the component's constructor) like this:

this.order = router.getCurrentNavigation()?.extras.state as Order;

It is accessible also after the navigation ends by using history.state.

You can also include a service for holding the state that you want to share between certain components.

  • Related