Angular 2 - passing data between routes

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

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

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

      

How can I pass formValues ​​(a Javascript object that contains the search criteria entered by the user) to the search results component? In the search results component, I search (using a service) and display the results to the user in a grid.

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

What's the best approach?

+3


source to share


2 answers


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

Your service might look something like this:



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.

0


source


Since your data is objects, you can use localstorage or a shared service to transfer it.



You can get an idea of ​​how to use the generic service here: fooobar.com/questions/240481 / ...

+1


source







All Articles