Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Angular 2 pass a complex object along the router?

Is it possible to send a complex object through a router? Here is what I'm doing and trying to do:

From the search page, a use can click a button on one of the results which calls the method that causes this line to fire. this.router.navigate(['profile-detail', selection]);

The selection object looks like this just before the navigate.

{
  profile: {
    id: number,
    fname: string,
    lname: string
  },
  contact: {
    type: string,
    address: string
  },
  books: [{
    title: string,
    author: string
  }]
}

However, when we get to the profile-detail page, the this.route.snapshot.params has this as the actual data:

{
  profile: "[object Object]",
  contact: "[object Object]",
  books: "[object Object]"
}
like image 380
Machtyn Avatar asked Jan 14 '17 15:01

Machtyn


People also ask

Can we pass data in router-outlet in Angular?

There are various ways by which we can pass data from one component to another. Angular 7.2. 0 introduced a new way to pass data using State Object while navigating between routed components.

What would you use in Angular 2 to define routes?

We use the router-outlet directive, an Angular 2 Routing directive that displays the active route (like ng-view ).


1 Answers

No, the router needs to serialize the data to the browsers URL bar, and the URL bar only supports a string.

You can use a shared service to pass objects between components that are not parent/child or siblings or dynamically added like the router does.

See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

A resolver might also work depending on your concrete requirements https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard

like image 134
Günter Zöchbauer Avatar answered Oct 21 '22 08:10

Günter Zöchbauer