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.

`api.service.ts`

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

@Injectable()
export class APIService {
    url = 'https://hemstreet.io/api';

    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.http.post(`${this.url}/${path}`, data, options)
            .map((res: Response) => res.json());
            })
    }

    getData(data: any): Observable<any> {
        return this.post(
            data,
           'all-your-base'
        );
    }
}

`blah-blah.component.ts`

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

@Component({
    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'})
            .subscribe(console.log);
    }
}

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.

Jon

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...