import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class DataService { constructor(private http: Http) {} getData(): Observable{ return this.http.get('https://jsonplaceholder.typicode.com/posts') .map(response => response.json()); } }
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class DataService { constructor(private http: Http) {} postData(data: any): ObservableThis example uses the Http module's `post()` method to make a POST request to an external API. The `Headers` and `RequestOptions` classes are used to set the appropriate headers and options for the request. The package library for the @angular/http module is @angular/http.{ let headers = new Headers({'Content-Type': 'application/json'}); let options = new RequestOptions({headers}); return this.http.post('https://jsonplaceholder.typicode.com/posts', data, options) .map(response => response.json()); } }