Angular Observable

observables works as an interface to handle the different types of asynchronous operations.

Observable is a part of rxjs. It is mainly used to handle server request and response either synchronously or asynchronously manner.
OR
HTTP module use Observable to handle the API request and response.

There are some steps to define observable.

Step1) Suppose, You created 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');
}
}

Step2) Now subscribe getUserList() method into 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 a application through 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 into 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 console.

Output:- Hello Friends

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

unsubscribe() method

Observable used 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');
    } );

  }