I'm streaming

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.

An inventive, entrepreneurial and positively unsatisfied mind that constantly pushes the tech boundaries to create new solutions and devices that change people’s lives.

Leave a Reply