Reputation: 11
In my angular app, I store my state in a signal in a singleton service. If a component/service of my app needs this state, it simply injects the service and "binds" to the signal. In my case, the state is list. I define the type of the list as list or null. The purpose of null is to disambiguate between the list being empty because there is no data, and the list being empty because the data has not been initialized yet. Thus I default the state to null, and once initialized, the state is becomes a list. I don't want my components to check for null, I just want them to deal with a list. I also want the app to throw an error if a component access the state when it is null. To implement these requirements, I came up with the following solution:
private _items = signal<Item[] | null>(null);
items = computed(() => {
const items = this._items();
if (!items) {
throw new Error("The items have not been initialised");
}
return items;
})
The above code is in my singleton service. The components access the items
signal.
I was wondering if my solution is considered best practice, or if there are any subtle pitfalls I have missed.
Upvotes: 0
Views: 101