Requests as Promises

The observable returned by Angular http client can be converted it into a promise.

We recommend using observables over promises. By converting to a promise you will be lose the ability to cancel a request and the ability to chain RxJS operators.
  1. import { Http } from '@angular/http';
  2. import { Injectable } from '@angular/core';
  3. import 'rxjs/add/operator/map';
  4. import 'rxjs/add/operator/toPromise';
  5. @Injectable()
  6. export class SearchService {
  7. constructor(private http: Http) {}
  8. search(term: string) {
  9. return this.http
  10. .get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
  11. .map((response) => response.json())
  12. .toPromise();
  13. }
  14. }

We would then consume it as a regular promise in the component.

  1. @Component({ /* ... */ })
  2. export class AppComponent {
  3. /* ... */
  4. search() {
  5. this.searchService.search(this.searchField.value)
  6. .then((result) => {
  7. this.result = result.artists.items;
  8. })
  9. .catch((error) => console.error(error));
  10. }
  11. }

原文: https://angular-2-training-book.rangle.io/handout/http/requests_as_promises.html