简体   繁体   中英

How to save images when navigating in Angular SPA?

I'm using Angular's router to navigate between components, thought when I'm going back, the components reload. I solved the content issue by saving the content array in a service and loading it from there, so it doesn't have to call the server every single time. But I don't know what to do with images, they are received from the server as a base64 string, and then shown in the image, but how do I cache/save them or in what form should I keep them in memory in order to instantly load them again when navigating back to the component that contains them? I looked online but didn't know what terms to use in order to search for a solution.

The component you are looking for is either sessionStorage or localStorage (you could also play around with cookies, but I find the previously mentioned ways easier to use):

  • Session: Stored until the browser window is open
  • Local: Persisted, even when the browser is closed.

Regardless of what kind of these storages you use, the data contained actually is the same, consisting of key-value pairs.


localStorage and sessionStorage are no built-in Angular features, you can imagine it more like an API provided by Java/TypeScript . For a detailed description of this API, have a look at here and here .


You can easily see what a website is storing on your machine by pressing F12 and navigating in the developer options.


I have created a simple example here .

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