简体   繁体   中英

How to store data when navigating between multiple pages in Angular?

I have the following problem in Angular. If I have two pages A and B each containing a table. Then I make changes to Page A in the table, and then navigate to Page B. Now I expect that when I navigate back to Page A, the changes are still there. I don't want to send the changes to the database until I click a save button. What is the best way to solve this in angular?

I don't recommend to use localStorage for your task if you develop SPA application, because localStorage / sessionStorage is limited and it is designed for another purposes - like authentication etc. But of course if you need to preserve your data - like cookie/JWT token etc. even after refreshing the page you can use localStorage .

I recommend to use Angular services for this: please see examples at docs Services/DI docs . Once you registered service as a singleton Singleton services , you can inject it via built-in DI(Dependency Injection) in component which renders your table at page A. But of course, you are not limited in injection only in component which located at page A, you can inject it even in page B etc.

If you are only wanting to preserve the data for this one instance, then definitely look to using a Service and writing your data to localstorage for it to persist across page refreshes.

If you are developing a SPA, then I'm not sure why you need it to persist across a page refresh since moving between components does not actually send a new HTTP request. You state should be preserved in your Service.

If you find yourself needing to manage state across your entire application and want to do it reactively, I recommend checking out NGRX.

https://ngrx.io/

Another alternative that maybe has a little less boilerplate is NGXS, which does the same thing as NGRX.

https://www.ngxs.io/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM