Angular 2 observable http requests

The following is a trimmed down example of how to get an http service up and running with Angular 2.


import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs';

export class APIService {
    url = '';

    constructor(private http: Http) {}

    post(data: Object, path: string): Observable<any> {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return`${this.url}/${path}`, data, options)
            .map((res: Response) => res.json());

    getData(data: any): Observable<any> {


import { Component, OnInit } from '@angular/core';
import {APIService} from "../api/api.service";

    selector: 'blahblah',
    templateUrl: './blahblah.component.html',
    styleUrls: ['./blahblah.component.scss']

export class BlahBlahComponent implements OnInit {

    myData = [];

    constructor(private apiService: APIService) {}

    ngOnInit() {
        this.apiService.getData({blah: 'bar'})

When executing an http request from angular 2’s http component. Make sure to subscribe to the http request for it to execute. Everything may look right as far as parameters being passed but it will never execute until something is subscribed to it.


Innovative, entrepreneurial and positively unsatisfied mind that constantly pushes the tech boundaries to create new solutions and devices that change people’s lives. Throughout my career, I have had the opportunity of having a multi-disciplinary experience, which led me to wear the hats of: Architect, IoT Consultant (Internet of Things Consultant), Developer, Designer, Engineer, Server Admin, Consultant and Project Manager – to name a few. Based on this diversified background, I get projects done by following smart ideas and well-planned goals. In a world which is getting more unconventional by the day, I use unconventional ways, and a very healthy dose of integrity, to create devices and solutions that help companies go from a steady present to a dynamic future.

You may also like...