简体   繁体   English

Angular 2 - 在路由之间传递数据

[英]Angular 2 - passing data between routes

I have 2 routes in my application - /search/criteria and /search/results. 我的申请中有2条路线 - / search / criteria和/ 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. 此按钮调用函数(onSearch),表单值作为输入传递。 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? 如何将formValues(包含用户输入的搜索条件的Javascript对象)传递给搜索结果组件? 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. 由于搜索执行是在服务中完成的,我也可以从onSearch方法调用此服务。 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? 什么是更好的方法?

Since your data is an object, you could use localstorage or a shared service to transfer it. 由于您的数据是对象,因此您可以使用localstorage或共享服务来传输它。

You can get an idea of how to use a shared service from here: https://stackoverflow.com/a/35479148/6835976 您可以从这里了解如何使用共享服务: https//stackoverflow.com/a/35479148/6835976

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. 我建议创建类似DataStorageService的东西,在其中存储搜索条件组件中所需的数据,然后从您需要它的服务中提取数据。

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. 当然,这是一个简单的示例,您需要决定如何将数据存储在服务中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM