Converting Signals to Observables in Angular 16
Angular v16 includes the new package rxjs-interrop, which has a useful method called toObservable, that enables developers to convert a signal to an observable. This post will look at the new functionality and how it may be utilized.
First, we must import the @angular/core/rxjs-interrop
module's toObservable method. Here's an example of code that shows how to use it:
import { toObservable } from '@angular/core/rxjs-interop';
import { signal } from '@angular/core';
@Component({
standalone: true,
template: `
<input (input)="$q.set(input.value)" #input />
`,
})
export class FooComponent {
$q = signal('');
obs$ = toObservable(this.$q);
ngOnInit() {
this.obs$.subscribe(console.log);
}
}
We make a signal with an empty string as its first value and then use the toObservable method to turn it to an observable. Then, we subscribe to the observable and log its value whenever it changes.
The toObservable function, on the inside, produces a ReplaySubject and wraps the specified signal in an effect. When the value of the signal changes, the effect will emit the new value.
-
Date: