Angular Observable

In Angular, Observables are a key concept for handling asynchronous operations, provided by the rxjs (Reactive Extensions for JavaScript) library. Observables allow you to work with data streams, making it easier to manage asynchronous events such as HTTP requests, user inputs, or time-based data sequences.

OR

Observable is a part of rxjs. It is mainly used to handle server requests and responses synchronously or asynchronously.

Concepts of Angular Observables:

1. What is an Observable?

An Observable is a stream of values (emitted over time) that can be observed or subscribed to.

Observables are lazy, meaning they do not emit data until they are subscribed to.

2. Creating Observables

Observables can be created using the Observable.create() or other helper functions like of(), from(), interval(), etc.


import { Observable, of } from 'rxjs';
const myObservable = of(1, 2, 3, 4, 5); // Emits 1, 2, 3, 4, and 5

3. Subscribing to Observables

To receive data from an Observable, you need to subscribe to it.

The subscribe() method takes three arguments: next, error, and complete.


myObservable.subscribe({
   next: (value) => console.log(value),
   error: (err) => console.error(err),
   complete: () => console.log('Completed!')
});

4. Unsubscribing from Observables

To prevent memory leaks, especially in Angular, it’s important to unsubscribe from Observables when they are no longer needed.


const subscription = myObservable.subscribe(value => console.log(value));
subscription.unsubscribe();

5. Observable Operators

Operators in rxjs allow you to transform, filter, combine, and work with Observable data streams.

some operators like

map(): transforms the values emitted by an Observable.

filter(): filters values based on a condition.

mergeMap(): projects each value to an Observable, and flattens all Observables into a single stream.

switchMap(): switches to a new Observable when a new value is emitted.


import { map, filter } from 'rxjs/operators';

const example = myObservable.pipe(
   filter(value => value % 2 === 0),
   map(value => value * 10)
);
example.subscribe(value => console.log(value)); // Output: 20, 40

Observables in Angular Services

HTTP module uses Observable to handle API requests and responses.

There are some steps to define observable.

Step1) Suppose, You create a user.service.ts file and create the function getUserList() into this.


import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable, throwError} from 'rxjs';


Injectable({
 providedIn: 'root'
})

export class UserService{
// Backend API URL
public apiURL="http://localhost:9200";

constructor(private http:HttpClient){}

getUserList() : Observable<any>{
return this.http.get(any)(this.apiURL+'/user-list');
}
}

Step 2) Now subscribe getUserList() method in the app component.


import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {UserService} from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

user_details:[];
 constructor(private router: Router
    public _userService:UserService) { 
      this.userListData(); 
     }
userListData(){

    return this._userService.getUserList().subscribe((res) => {
   
        if(res.status == 200) {
   
          this.user_details=res.data;
           
         }
   
       }, (err) => {
          console.log(err);
     });
   
     }

}

Observable Methods

Observable is also used to pass the value in an application through the next() method.

1) next():- this method is used for pass the value into application.
2) error():- this method is used for error notification.
3) complete():- this method is used to complete notification.

Now, add the below code to the component app.component.ts file


import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  observableData:any;
  constructor() { }

  ngOnInit(): void {
    const observable= new Observable((data) =>{
      data.next("Hello");
      data.next("Friends");

    });

    observable.subscribe(res =>{
        console.log(res)
       
    } );
  }

}

Now, run the code and check into the console.

Output:- Hello Friends

Note:- In Observable, you can pass multiple values through the next() method.

unsubscribe() method

Observable used the unsubscribe() method to stop the execution.


 const observable= new Observable((observer) =>{
      observer.next("Hello");
      observer.next("Friends");
      observer.complete();
    });

   observable.unsubscribe(res =>{
        console.log('stop the execution');
    } );

  }