Search code examples
javascriptangularpostroutesangular7

Navigate in Angular 7 without adding parameter to URL


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.


Solution

  • 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;
        ...
    }