Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  178] [ 5]  / answers: 1 / hits: 24902  / 6 Years ago, wed, november 28, 2018, 12:00:00

I want to navigate between two routes in Angular 7 with posting data between them. But I don;t want to show those parameter in URL. How to do it in proper way?



at this moment I am strugging with something like this:




this.router.navigate(['/my-new-route', {data1: 'test', test2: 2323, test: 'AAAAAAA'}]);



and it change my url to




http://localhost:4200/my-new-route;data1=test;test2=2323;test=AAAAAAA



how to do it to cancel those data from url:




http://localhost:4200/my-new-route



Edit:



My case:




  1. /form - route with some form

  2. /options - route with some data



on /form route - users have some form with empty fields to fill manually



but on /options page there is some preset configuration, when user choose one is navigated to /form and fields are fill autmatically



when they move back to another page and back again to /form - should see empty form. Only link from /options to /form should fill those fields.


More From » angular

 Answers
15

You can create a service and share it between both the components (the one that you're moving from, and the one that you're moving to).



Declare all the parameters that you want to pass to the URL, in the service, and before the router.navigate([]), set the values for parameters in the service.



You can access those parameters from the other component with that service.



Example:



SharedService



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

@Injectable({
providedIn: 'root'
})
export class SharedService {
data1;
test2;
test;
}


Component1



import { SharedService } from 'location';
import { Router } from '@angular/router';
...
constructor(private _sharedService: SharedService,
private _router: Router) { }
...
this._sharedService.data1 = 'test'
this._sharedService.test2 = 2323;
this._sharedService.test = 'AAAAAAAA';
this._router.navigate(['/my-new-route']);
...


Component2



import { SharedService } from 'location';
...
private test2;
private test;
private data1;
constructor(private _sharedService: SharedService){ }
ngOnInit() {
this.data1 = this._sharedService.data1;
this.test2 = this._sharedService.test2;
this.test = this._sharedService.test;
...
}

[#53025] Friday, November 23, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dorothylorrainef

Total Points: 456
Total Questions: 102
Total Answers: 115

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;