Angular

change route params without reloading browser in angular

Spread the love

I have face this problem when I kept my apps data in route param and that require to change (when user change apps data that present in apps route) route param data when navigate to different route or when click browser back. If you do not change your apps data accordingly that present in apps route then your apps will not work accordingly. Here below coding may help you to work your app.

You can also use angular replace state when require to change route param without navigate or reload window.


const url = this._router
			.createUrlTree([], {
			   relativeTo: this._route,
			   queryParams: this.routeParams
		        }).toString();


this.location.replaceState(url);

browser back route to push state in angular

import { Location } from '@angular/common';
import {
	ActivatedRoute,
	NavigationExtras,
	Router,
	RoutesRecognized
} from '@angular/router';
import { Subscription, Observable, forkJoin } from 'rxjs';

constructor(private location: Location){
   this.getRouteQueryParams();
   this.getRouteOnChange();
 }

public onChangeAnyExistingRouteData(){
    this.location.go();
    //this.location.replaceState('/profile');
}


private getRouteQueryParams() {
	this.subscriptions.push(
	this._route.queryParams.subscribe({
	   next: (params) => {
	   this.routeParams = JSON.parse(JSON.stringify(params));
	  }
	}));
}

// if needed to change url params before navigation away from a route

private getRouteOnChange() {
   this._router.events
	.pipe(
		filter((e) => e instanceof RoutesRecognized),
			map((e) => <RoutesRecognized>e))
			.subscribe((e) => {

			let navigationExtras: NavigationExtras = {
			  queryParams: {
			   ...this.routeParams
			  }
			};
			const url = this._router
			.createUrlTree([], {
			   relativeTo: this._route,
			   queryParams: this.routeParams
		        }).toString();
			this._router.navigate([e.state.url], navigationExtras);
			window.history.pushState({}, '', url);
   })
}

References

Thank you for reading! Like our Facebook page for get more updates instant.


Spread the love

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

Leave a Reply

Your email address will not be published. Required fields are marked *