What Is The Difference Between Observable And Promises.

Posted By : Monu Thakur | 29-Mar-2018

There is some confusion when promises are applied since the introduction of Angular2 systems, while the observables are used for our use, while comparisons of these two methods have some doubts.


Promise

Promises work asynchronous and return a single value or error message. Another important thing to remember about promises is that you can not undo the initiated request.

 

There are also major differences between the use of the promise or the observation. Because we can not undo the collateral, the HTTP request sought, for example, when we enter the key, we will then run the keys several times to press.

 

Here's a very simple example demonstrating that:


 

<!-- app.component.html -->
<div>
  <h2>Star Wars Character Search</h2>
  <input #term type="text" (keyup)="search(term.value)">
  <hr>
  <div *ngIf="results.length > 0">
    <li *ngFor="let result of results">{{ result.name }} is a character with a height of {{ result.height }}.</li>
  </div>
</div>


// app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  private results = [];
  constructor(private http: HttpClient) { }

  private search(term) {
    console.log(term);
    this.http.get(`https://swapi.co/api/people/?search=${term}`).toPromise()
    .then((data: any) => {
      /* tslint:disable:no-console */
      console.time('request-length');
      console.log(data);
      console.timeEnd('request-length');
      this.results = data.results;
    });
  }
}

 

 

Promises are their use cases and we can use them when they request a cancellation request. Also, make sure you use the asynchronous / expected feature to help asynchronous code write.


Observables

 

 

Observation is a river and the oath limits the ability to resist. The box supports operators such as map () and filters ().

 

 

Angular can observe Rx.js and are used instead of frames instead of as collateral for HTTP requests. Therefore, in the preceding example, toPromise () need to be specified for commitments to be visible in the commit.

 

 

To use ReactiveForms we have to make the first change. This allows us to make changes to the input fields:


 

<!-- app.component.html -->
<div>
  <h2>Star Wars Character Search</h2>
  <input [formControl]="term">
  <hr>
  <div *ngIf="results.length > 0">
    <li *ngFor="let result of results">{{ result.name }} is a character with a height of {{ result.height }}.</li>
  </div>
</div>

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormControl } from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

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

  private results = [];
  private term = new FormControl();
  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.term.valueChanges
      .debounceTime(400)
      .distinctUntilChanged()
      .subscribe(searchTerm => {
        this.http.get(`https://swapi.co/api/people/?search=${searchTerm}`).subscribe((data: any) => {
          /* tslint:disable:no-console */
          console.time('request-length');
          console.log(data);
          console.timeEnd('request-length');
          this.results = data.results;
        });
      });
  }
}

 

Please use DebounceTime () and distinctUntilChanged (). The first method allows the exclusion of emissions between less than 400 millecards of output, while the second method indicates that its name reflects the value until the value changes.

 

 

Then we log in to these changes and then we called the API, and the API has been ordered. Now, let's check that there is only one request for the checking account.

Thanks

 

 

About Author

Author Image
Monu Thakur

Monu is an experienced Frontend Developer, having good knowledge of Photoshop, illustrator, HTML5, CSS3, Less, Sass, Javascript, Jquery, Angular 4, Angular 4 theme integration.

Request for Proposal

Name is required

Comment is required

Sending message..