Making HTTP Requests

To make HTTP requests we will use the Http service. In this example we are creating a SearchService to interact with the Spotify API.

  1. import { Http } from '@angular/http';
  2. import { Injectable } from '@angular/core';
  3. import { Observable } from 'rxjs/Observable';
  4. import 'rxjs/add/operator/map';
  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. }
  13. }

View Example

Here we are making an HTTP GET request which is exposed to us as an observable. You will notice the .map operator chained to .get. The Http service provides us with the raw response as a string. In order to consume the fetched data we have to convert it to JSON.

In addition to Http.get(), there are also Http.post(), Http.put(), Http.delete(), etc. They all return observables.

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