7

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]"
}
Machtyn
  • 2,982
  • 6
  • 38
  • 64

2 Answers2

7

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • @TimConsolazio `EventEmitter` is supposed to be only used with `@Output()` in components. In services use observables instead. http://stackoverflow.com/a/35568924/217408, https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html – Günter Zöchbauer Jan 14 '17 at 16:11
  • 1
    Thanks, I had seen a similar answer in other similar questions. But your explanation on serialization was missing from those other answers. – Machtyn Jan 14 '17 at 16:17
  • Again, Angular 1.x recommended many things the field in general abandoned. And for the record, I found it extremely constructive. – Tim Consolazio Jan 14 '17 at 16:26
  • 1
    Subject is `RxJS` – Günter Zöchbauer Jan 14 '17 at 16:38
1

another can be using JSON.stringify and save your object in local storage or session storage and have it widely available in entire app

Amir Ghezelbash
  • 2,195
  • 15
  • 24