kayasa
kayasa

Reputation: 2085

Angular 2 - passing data between routes

I have 2 routes in my application - /search/criteria and /search/results.

In the search criteria component, user fills the search criteria and clicks on the search button. This button calls a function (onSearch) and the form values are passed as an input. It then routes the user to search results component.

onSearch(formValues) {
 console.log(formValues);
 this.router.navigate(['/search/results']);
}

How can I pass the formValues (Javascript object which contains search criteria entered by the user) to the search results component? In the search results component, I would be executing the search (using the service) and displaying the results to the user in a grid.

Since the search execution is done in a service, I could also call this service from the onSearch method. But then the question would be how to pass the results to the search results component (so that it can render them in a grid).

What would be a better approach?

Upvotes: 3

Views: 5767

Answers (2)

Kerim Emurla
Kerim Emurla

Reputation: 1151

I would suggest creating something like a DataStorageService where you store the data you need in search criteria component and then just extract the data from the service where you need it.

Your service could look something like this for example:

import { Injectable } from "@angular/core";

@Injectable()
export class DataStorageService {
    public storage: any;

    get isEmpty(): boolean {
        return this.storage === null || this.storage === undefined;
    }

    constructor() {}
}

Of course this is a simple example and you need to decide how you really want to store your data in the service.

Upvotes: 0

Olezt
Olezt

Reputation: 1738

Since your data is an object, you could use localstorage or a shared service to transfer it.

You can get an idea of how to use a shared service from here: https://stackoverflow.com/a/35479148/6835976

Upvotes: 1

Related Questions