12

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?

1
  • 6
    Use a shared service. Commented May 8, 2017 at 12:13

2 Answers 2

8

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/

Sign up to request clarification or add additional context in comments.

4 Comments

Would Redux be a better approach in this case? I'm always in doubt which one should I use on scenarios like this... Any thoughts on that?
The Redux pattern is a commitment and if you opt to use it, it is best used for all of your application state. If you just need a simple solution, a service is a good way to go. If you want to buy into the Redux pattern, then NgRx is a great way to handle this.
Hi @DeborahK what do you prefer now still use a service to share the data or by using state property ? or is there a new way ?
Yes, I use a service to share all of the data in my application. Within the service I may use a state property, or if I'm managing streams, an Observable operator such as shareReplay.
1

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

2 Comments

On Refresh will loose the data
also if you use a shared service this the same @user630209

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.