connect is a utility function that connects a signal to an observable and returns a subscription. The subscription is automatically unsubscribed when the component is destroyed. If it’s not called in an injection context, it must be called with an injector or DestroyRef.
Usage
It can be helpful when you want to have a writable signal, but you want to set its value based on an observable.
Connect with observables
For example, you might want to have a signal that represents the current page number, but you want to set its value based on an observable that represents the current page number from a data service.
Connect with observables not in an injection context
You can also use it not in an injection context, but you must provide an injector or DestroyRef.
Connect with other signals
This is useful when you want to have a writable signal, but you want to update its value based on another signal that represents the current state of that value.
For this to work, the second argument must be a callback function that includes a signal call inside of it.
Object Signal
There are cases where we construct a single Signal to store a state object. connect can also work with object signals
ConnectedSignal
A ConnectedSignal allows you to connect any number of streams to a signal
during or after the initial connect call.
A benefit of this approach is that it allows you to connect multiple streams to
a signal whilst utilising different syntax for the connect call.
For example, if your streams directly emit the values you want to set into the
signal, you can use this syntax:
Or, if you need to use a reducer to access the previous signal value, you can
use this syntax:
However, if you want to use multiple different streams with different reducers,
you would need to use multiple connect calls (one for each reducer you want to
add), e.g:
With a ConnectedSignal you can use the with syntax to chain these into
a single connect call:
This allows for any combination of streams without reducers and streams with
different types of reducers.