简体   繁体   中英

A simple definition for Observable and Promise in Angular 4

I really want to know completely and simply about Observable and Promises in Angular. Thanks for anybody to tel me with a simple example.

Recommend Reading through the angular docs on http here link This answer comes from the Docs.

The Angular http.get returns an RxJS Observable.(You don't need Observables for HTTP requests, since it's 1 request and 1 response) An Observable is a stream of events that you can process with array-like operators. Converting to a Promise is often a good choice. You typically ask http.get() to fetch a single chunk of data. When you receive the data, you're done. The calling component can easily consume a single result in the form of a Promise.

Here is a simple example: .../app/http.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class HttpService {

constructor(private _http: Http) { }
retrieveTasks() {
    return this._http.get('/tasks').map(data=>data.json()).toPromise()
  }
}

Notice that the _http.get() has 2 functions chained to it, .map and .toPromise() . The .map method is used to convert the returned object from the HTTP request into a json formatted object, and the .toPromise method is used to force the _http.get() call to return us a Promise instead of an Observable. No need to use the Observable's benefits in basic HTTP requests, keep it more clean and simple with Promises.

You can look at this answer from @Gunter he explains it in a very simple manner

https://stackoverflow.com/a/37365955/2708210

Just to add a sample code for the two

Observable

getLukeSkywalkerObservable(){
    return this.http.get('http://swapi.co/api/people/1/')
      .map(res => {
        return  res.json(); // using maps to filter data returned form the http call
      }).map(data => {
        return data; // using maps of maps to filter data returned form the map
      }).flatMap((jedi) => this.http.get(jedi.homeworld))
      .map(res => {
        return res.json().name; // using flat maps to combine data returned from two observables into one
      }).catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

Promises

getLukeSkywalkerPromise(){
    return this.http.get('http://swapi.co/api/people/1/').toPromise()
      .then((data) => {
        console.log(data); // binding the result from the promise
        return data.json();
      }).then((data) => {
        console.log(data.name); // more like map of map but limited functionality
        return data.name;
      }).catch((ex) => {
          console.error('Server Error'+ex);
      })
  }

Promise:- In simple word 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. Observables:- Observables provide support for passing messages between publishers and subscribers in your application. Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values. Supports collection operators like map, filters. Following features available ES 2016. Always can be canceled. Using RX JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM