Angular + RxJS - subscribe()
December 16, 2023
1. subscribe()
is a method of RxJS Observable
class.
2.
subscribe()
invokes an execution of an Observable
and registers Observer
handlers for notifications it will emit.
3. When we call
subscribe()
method, only when Observable
instance starts working.
4. Suppose we have to get data from HTTP URL and display on UI, Angular
HttpClient.get()
is used to create an Observable
that will execute when we call its subscribe()
method.
5. After execution,
subscribe()
listens for the values emitted by Observable
as well as for when it completes or throws errors.
Parameters
Thesubscribe()
method accepts an RxJS Observer
that is a consumer of values delivered by an Observable
. The Observer
is a set of callbacks, one for each type of notification delivered by the Observable: next, error, and complete.
Find the parameter of
subscribe()
method as Observer
.
subscribe({ next: (value: T) => void, error: (error: any) => void, complete: () => void });
Observable
. It is optional to use and default is undefined. If we omit this field, we will will not be able to receive values.
2. error : Listens for any error thrown in execution of
Observable
instance. It is optional to use and default is undefined. If the error field is not provided and an error happens, it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using try/catch.
3. complete : Listens for execution completion even if there is error. It is also optional to use.
Examples
1. Using only nexta. Simple code with next field.
of("Welcome!").subscribe({ next: (data: string) => console.log(data) });
of("Welcome!").subscribe({ next: (data: string) => { console.log("Inside next"); console.log(data); } });
of("Welcome!").subscribe( (data: string) => console.log(data) );
2. Using only next and error
constructor(private http: HttpClient) { } ngOnInit() { const url = "http://localhost:4200/students"; const studentRecords$ = this.http.get(url); studentRecords$.subscribe({ next: (data: any) => console.log(data), error: (err)=> console.log("Error occurred: ", err) }); }
3. Using next and complete
studentRecords$.subscribe({ next: (data: any) => console.log(data), complete: ()=> console.log("-- complete --") });
4. Using next, error and complete
studentRecords$.subscribe({ next: (data: any) => console.log(data), error: (err)=> console.log("Error occurred: ", err), complete: ()=> console.log("-- complete --") });
If studentRecords$ executes unsuccessfully, error and complete field will execute.