Blog

You are here: Blog / Difference Between Observable and Promise in Angular


  • Difference Between Observable and Promise in Angular

    Promise:

    Promise handles a single event when an async operation completes or fails.

    Promises work with asynchronous operations. They either return a single value or an error message, success message (the promise resolves) or an error message (the promise rejects).

    • Not easy to cancel.
    • User could not retry a failed call.
    • Having one pipeline
    • Usually only use with asynchronous data return

    Observable:

    Observables provides support for passing messages between parts of your app. They are mostly used in Angular and are the recommended technique for event handling, asynchronous programming, and handling multiple values.

    Observable is array or a sequence of events over time. It has at least two participants, the creator (the data source) and the subscriber (subscription where data is being consumed).

    • Are cancellable.
    • User could retry a failed call such as retry and retryWhen.
    • Stream data in multiple pipelines
    • Provides the map, forEach, filter, retry and retryWhen operators

    Here consider that API project has already been created. Here is sample Code for API project which has been use in angular application.

     	[HttpGet]
        [Route("getSearchedCompany")]
        public List getSearchedCompany(string keyword)
        {
            List companyresult = new List();
            using (var db = new MasterKeepTruckInEntities())
            {
                companyresult = db.searchCompanyByName(keyword).ToList();              
            }
            return companyresult;
        }

    Angular web application:

    Step 1: Create workspace and initial application

    Run the following command in terminal / command line

    PS E:\> ng new example

    Step 2: Add component (promise-example)

    Run the following command in terminal / command line

    PS E:\> ng g c  promise-example

    Step 3: Now open the promise-example.component.html file and add the following code.

    <div style="text-align: center;">
        <h1>
            Example of Fetching data using Promise
        </h1>
        <div>
            <h2>
                Company Name Search
            </h2>
            <input #term type="text" (keyup)="searchCompanyUsingPromise(term.value)">
            <div>
                <li *ngFor="let result of Company">
                    {{result.CompanyName}}
                </li>
            </div>
        </div>
    </div>
    

    Step 4: Now open the promise-example.component.ts file and add the following code.

    export class PromiseExampleComponent implements OnInit {
      Company: any;
      constructor(private _CompanyService: CompanyService) { }
    
      ngOnInit(): void {
      }
      public searchCompanyUsingPromise(keyWord) {
        this._CompanyService.getSearchedCompany(keyWord).toPromise()
          .then((data: any) => {
            debugger
            console.log(data);
          });
      }
    }
    

    Step 5: Add component (observable-example)

    Run the following command in terminal / command line

    PS E:\> ng g c observable-example

    Step 6: Now open the observable-example.component.html file and add the following code.

    <div style="text-align: center;">
        <h1>
            Example of Fetching data using Observable
        </h1>
        <div>
            <h2>
                Company Name Search
            </h2>
            <input type="text" [formControl]="term">
            <div>
                <li *ngFor="let result of Company">
                    {{result.CompanyName}}
                </li>
            </div>
        </div>
    </div>
    

    Step 7: Now open the observable-example.component.ts file and add the following code.

    export class ObservableExampleComponent implements OnInit {
      country: any;
      constructor(private _CompanyService: CompanyService) { }
      private term = new FormControl();
      ngOnInit(): void {
        debugger
        this.term.valueChanges
          .subscribe(searchText => {
            this._CompanyService.getSearchedCompany(searchText).subscribe((result) => {
              console.log(result);
              this.country = result;
            })
          })
      }
    }

    Step 8: Add service (company service)

    Run the following command in terminal / command line

     PS E:\> ng g s company

    Step 9: Now open the company.service.ts file and add the following code.

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    @Injectable({
      providedIn: 'root'
    })
    export class CompanyService {
      employees: any[];
      private url = '';
      private baseUrl = "https://localhost:44360/";
      Company: any;
      constructor(public http: HttpClient) { }
      getSearchedCompany(keyWord) {
        debugger
        this.url = this.baseUrl + 'api/Company/getSearchedCompany?keyword=' + keyWord;
        return this.http.get<:any[]>(this.url);
      }
    }
    

    Step 10: Now open the app.module.ts file and paste the following code.

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { ObservableExampleComponent } from 	‘./observable-example/observable example.component’;
    import { PromiseExampleComponent } from './promise-example/promise-example.component';
    import { CompanyService } from './company.service';
    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
      declarations: [
        AppComponent,
        ObservableExampleComponent,
        PromiseExampleComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule
      ],
      providers: [CompanyService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Step 11: Now open the app.component.html file and add the following code.

    <app-promise-example></app-promise-example>
    <app-observable-example></app-observable-example> 
    

    Step 12: Run the angular application using below command :

    Please make sure your API project is running.

    PS E:\> ng  serve

    Output 1:

    Output 2: