If you’ve ever tried to convert an Observable into a Signal using the toSignal() function, you might have encountered the following error NG0203: toSignal() can only be used within an injection context:

This happens when you create an Observable outside of an injection context, which can happen if you want to download data when the user clicks on a button, for instance:

Can we make this work? Absolutely! The key is to access our injector and store it in a variable so we can pass it as a parameter to toSignal()
. How to do that?
Interestingly enough, we can access our injector by… injecting it into our component:

Then, we pass it as an option to the toSignal()
function:

And that’s it, problem solved! You can see the full code example on Stackblitz.