Rose Nettoyeur
Rose Nettoyeur

Reputation: 919

Angular2: Pass data between routes without a shared service

I have two routes. One is the "parent"-route and one the "child"-route. The parent-route is always loaded first and if the user wants to navigate to the child-route the content of the child-route is loaded.

Both routes need a special object "myObject". The parent route always has this object. Now I want to pass "myObject" to the child route.

  1. I cannot use route.params because myObject is dynamically and a object (not just a simple string or number)
  2. I don't want to use a shared DataService were the parent-route stores myObject and the child-route retrieves myObject from it. This seems a bit overkill to me because myObject already exists and I simply want to pass myObject to the child-route.

Is there any possibility to solve this? Maybe with the help of Guards? I prefer a simply solution maybe like this:

this.router.navigate('my/url/to/navigate', myObject);

Upvotes: 1

Views: 1449

Answers (2)

Derlin
Derlin

Reputation: 9871

There is currently no elegant ways to do that.

If you really don't want a service, you can pass the data in json format.

Example (here, the json will appear in the url):

this.router.navigate(['/child-route'], {
    queryParams: {
    'myObject': JSON.stringify(myObject)
  }});

In your child component (in ngOnInit):

this.sub = this.route
  .queryParams
  .subscribe(t => {
    console.log(t['myObject']);
  });

Now, one limitation is that by serializing to JSON, you lose your class information.

In typescript, it is difficult to get back a class instance from a plain js object. I found this library, class-transformer, which seems to work (but I have no idea about the performances). So, to get back a ts instance in your child component:

import {plainToClass} from "class-transformer/index";


this.sub = this.route
  .queryParams
  .subscribe(t => {
    let o = <MyObject>JSON.parse(t['myObject']);
    this.myObject = <MyObject>plainToClass(MyObject, o);
  });

Now, this.myObject is of type MyObject.

Upvotes: 1

Joe Keene
Joe Keene

Reputation: 2351

You can pass a simple property into the params of the navigate call like so:-

this._router.navigate(['/route-location', {name: 'test'}]);

In your component on route you can subscribe to the params and get the value.

    this.route.params.subscribe((p) => {
        let params: any = p;
        console.log(params.name);
    });

If you want to pass more data etc then a service is the way to go.

Upvotes: 0

Related Questions