Introduction to Observables
To begin the discussion on Observables, let's first install the RxJS library as follows:
npm install rxjs
The RxJS library already includes the declaration files that are needed by TypeScript, so there is no need to install them separately using @types
.
To generate an Observable, we can use the of
function as follows:
import { of, Observable } from "rxjs";
const emitter : Observable<number> = of(1, 2, 3, 4);
Here, we start by importing the of
function and the Observable
type from the rxjs
library. We are then defining a constant variable named emitter
, which is using generic syntax to define its type as an Observable of type number
. We then assign the result of the of
function to the emitter variable, which will create an Observable from the numbers 1 through 4. We can now create an Observer as follows:
emitter.subscribe((value: number) => {
console.log(`value: ${value}`)
});
Here, we are calling...