puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

How to append and fetch Query Parameter from the URL #97

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

In the real application, we ofen meet the situations that, we need to apply the input's data to the URL as queryParameters. And when we copy this link to another tab, the browser should display the same page as previously.

Therefore here are two steps

Example

  1. Assume we have one component contains timezone, from and to date picker. Which will be applied to the table or other data for filtering.
  2. We use formGroup, formControl, moment for the date and timezone settings.

Step One

this function could be called inside the submit button or ngOnInit

 constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
    ){ }

private appendQueryParam(): void {
       // this part is only to fetch the value of each variable.
        const timezone = this.formGroup.controls.timezone.value;
        const from = this.fromToFormGroup.controls.from.value;
        const to = this.fromToFormGroup.controls.to.value;

        //this part is to encode the above values and append to URL
        this.router.navigate([], {
            queryParams: {
                from,
                timezone,
                to,
            },
            queryParamsHandling: 'merge',
            // preserve the existing query params in the route
            relativeTo: this.activatedRoute,
            skipLocationChange: false,
        });
    }

Step Two

this part is to fetch data from the already existing URL query parameter, and apply it to the input component.

this.activatedRoute.queryParams.subscribe((queryParams) => {
                    this.formGroup.setValue({
                        fromTo: {
                            from: moment(queryParams.from),    <==== 
                            to: moment(queryParams.to),
                        },
                        timezone: queryParams.timezone,
                    });
            },
        );

Notice above we need to use moment to transfer data type from string to moment.

When we obtain the data in the 1st step, and then console.log(queryParams), we could obtain something simliar as following. Notice, the three values are all string. When we need to use them from URL to component, we need to convert from and to into moment.

{timezone: 'Europe/Berlin', from:'156484165447', to:'234123531343'};

Cause normally when we set the date, we use the moment to regulate the data. Therefore here we have the from and to, so the interface of these from and to could be like this.

export interface Model {
    from: Moment;
    to: Moment;
}

Reference

[1] https://angular.io/guide/router#query-parameters-and-fragments