Shafaq Kazmi
Shafaq Kazmi

Reputation: 225

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?

Upvotes: 12

Views: 23774

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

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 🚀🚀

Upvotes: 1

DeborahK
DeborahK

Reputation: 60518

Here is an example of how to share data using a service: http://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

Upvotes: 8

Related Questions