typescriptangularangular2-routing

Pass objects during router navigate


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();
        }
    }
} 

Solution

  • 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