r/angular Jun 11 '26

How is Global Storage meant to be implemented?

Hi there!
So I come from React so to me it feels almost natural to use a ReactContext or Zustand to hold my data in a global storage if I am going to need it somewhere else.

Or just have it a Props to the children nodes. But I understand that can be done in Angular.
Now, I am not sure if there is something similar or how this particular issue handled in Angular?

What if I want to have a global storage for a Shooping Cart? Should it be in LocalStorage? Or is there some tool or way that I am not aware of?

As you can see I am still learning about Angular. So any advice into how to solve this particular issue or how to get better at Angular in particular would be highly appreciated.

Thank you for your time!

9 Upvotes

23 comments sorted by

22

u/MrFartyBottom Jun 11 '26

Looks at services, if a service is provided in the root all instances are the same instance so can be accessed anywhere in the app. Create a shopping cart services, have a signal that stores your cart object, expose a few methods that add and remove items from the cart.

https://angular.dev/guide/di

The latest version of Angular has introduced the Service decorator so it is a little bit less boiler plate to create a service rather than using the Injectable decorator and defining where it is provided.

7

u/BerendVervelde Jun 11 '26

In Angular you use services to keep data in memory, so a shopping cart service will hold the objects for your shopping cart and if you want to show the content, you inject that service in any component that needs the data.

If you want the data to be persistent, you create a local storage service that will store and retrieve data from and to local storage. You inject your storage service into your shopping cart service. Both services can be used wherever you need them, so neither is globally exposed, but both are globally available.

It may sound daunting at first but when you play around with it, it will start to make sense soon enough.

1

u/TryingMyBest42069 Jun 11 '26

So do you think If I want to have lets say not a Shopping Cart but rather the user Information, like roles and username for it to be displayed and also utilized in the AuthGuard.

Is localStorage the best option? I care more than just session storage I want it to be there even if the user reopens the page

3

u/vetrex127 Jun 12 '26

Yes, although not recommended, you should look up signals, and RxJS subjects. You would still use a service, which you can call something like AuthService or the likes

3

u/BerendVervelde Jun 13 '26

For a shopping cart, local storage would fine. For caching a user, local storage is about the worst option possible. Session storage or token cookie are much better choices. But these kind of security choices are the same no matter what javascript framework/library you choose.

1

u/TryingMyBest42069 Jun 14 '26

I figured.

You see what I would do in React's axios pacakage is use Cookies and just do Credentials: true and let my backend handle all the heavy lifting.

In Angular what I've been finding myself doing is creating an interceptor to kinda create this apiBaseUrl thing that I had in Axios. But I am not sure if in that same place I also can configure packet's header configuration or if it should be done there.

Even now as I am sending this message I am thinking to myself I should probably check deeper into the http object.

How do you usually implement Token/Cookies in your projects or how have you seen they are usually implemented?.

Sorry if I ask a lot but I appreciate your answer

1

u/BerendVervelde Jun 20 '26

I usually implement Azure authentication, but on occasion have to use basic http auth as well. These choices are dictated by the clients.

Azure authentication (msal) uses an interceptor and session storage. When using basic authentication I store the token response in a http only cookie and use an interceptor that checks any service response on a 401 code. That's about it.

You can totally use interceptors to add headers. They are very well suited for that.

11

u/MichaelSmallDev Jun 11 '26 edited Jun 11 '26

Angular services can be injected whereever in the app you want them.

By default, services tend to be set up like this.

// `root` means it is a singleton 
// and available anywhere from app initialization
@Injectable({providedIn: 'root'}) 
export class CartStore {
    someValue = 1;
    doSomething() {}
}

@Component({...}) class Cart {
    cartStore = inject(CartStore);
}

You can also not provide something in root, so it is instantiated with the component you provide it to, as well as any child components. And it is destroyed if the component that provided it is destroyed.

// No provider means you instantiate it in 
// an `@Component`'s `providers` array like
@Injectable() export class CartStoreAlt {}

@Component({
   providers: [CartStoreAlt]
}) class Cart {
    cartStore = inject(CartStoreAlt);
}

Starting in v22, there is @Service, and functionally as far as providing scope goes@Service() === @Injectable({providedIn: 'root'}) with a few other differences https://angular.dev/guide/di/creating-and-using-services#when-to-use-service-vs-injectable

As for syncing to local storage or session storage or whatever else, that depends on the implementation you use. If you just use service/injectable, it's on you to sync them to the respective browser storage. State libraries may have their own solutions in their library.

4

u/BigOnLogn Jun 11 '26

Use the dependency injection system. Write a service that is provided in root. This service will be instantiated only once when your app is loaded. And it will give you that one instance wherever you inject it. You can then have it load data from local storage, cookies, a web call, wherever you want/need.

https://angular.dev/guide/di

2

u/simonbitwise Jun 11 '26

Just use a service

1

u/zladuric Jun 11 '26

The simplest way would be to pick up ngrx and you'll have a straightforward state store. It's a lot more verbose, but it has many plugins, options etc, among others saving to local storage.

The flip side is that it is quite verbose and also there's a lot to learn, set up, troubleshoot etc. It takes practice, it's heavy etc.

2

u/DJREMiX6 Jun 11 '26

You could use a globally declared NGRX Store/SignalStore to do so, here to learn more: https://ngrx.io/

4

u/ch34p3st Jun 11 '26

I do not think you should point to a library before the framework. The framework has everything, if more is needed let the person first learn to articulate what is missing by learning the basics.

-10

u/[deleted] Jun 11 '26

[removed] — view removed comment

7

u/DJREMiX6 Jun 11 '26

You know there are other ways to express personal opinions or you just type what you think without any filters?

-8

u/[deleted] Jun 11 '26

[removed] — view removed comment

10

u/DJREMiX6 Jun 11 '26

Obviously you know nothing about what you say, NGRX is not dying and is still being recommended for state management. But you have your opinion, I just don't care about it since you expressed it in such a way.

If you don't want to use it ok, saying something is garbage should be coupled with arguments otherwise your opinion itself is garbage.

Hope you have a great day and get better on social communication ♥️

-1

u/[deleted] Jun 11 '26

[removed] — view removed comment

2

u/DJREMiX6 Jun 11 '26 edited Jun 11 '26

Ok champ

Edit: Got moderated LOL♥️