Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: Passing object to Routes without updating Query Params

I am using Angular 4 and I want to pass some object to router but without updating query params.

user.component.ts

this.router.navigate(["/profile",{
   action: 'edit',
   user: {id: 1, name: 'test', email: '[email protected]'}
}]);

app-routing.module.ts

{ path: 'profile', component: UserProfileComponent }

user-profile.component.ts

this.route.params.subscribe(params => {

});

Any help?

like image 543
Shafaq Kazmi Avatar asked May 08 '17 12:05

Shafaq Kazmi


People also ask

Can we pass object in query params in Angular?

Instead, you can pass the params as an object or an HttpParams instance.

Can we pass object in routerLink?

RouterLink for dynamic dataDynamic data or user-defined objects can be passed from Angular version 7.2 using the state object stored in History API. The state value can be provided using the routerLink directive or navigateByURL.

What is Queryparam in Angular?

The query parameters feature in Angular lets you pass the optional parameters while navigating from one route to another. When you pass a query parameter to a specific route, it looks something like this, http://localhost:4200/orders? category=watches.


1 Answers

In the latest version of angular 7.3 and above router navigate and navigateByUrl methods accept another parameter with type NavigationExtras has a property called state accept an object , after we set the state value we can get the value in the target component by access to history object so just like this we have pass an object betwwen routes.

set the state

 const user = {id: 1 , name : '...' , address : {country: '...' , city : '...'}}
 this._router.navigate([`details`,user.id] , {state:{...user} }); 

in the details component we can access the state value like this

 this.user = window.history.state;

stackblitz demo 🚀🚀

like image 107
Muhammed Albarmavi Avatar answered Sep 22 '22 17:09

Muhammed Albarmavi