Using http rest apis with angular 2

Well good answer provided by @langley but I would like to add some more points so posting as an answer.

First of all for consuming Rest APIs we need the Http and HTTP_PROVIDERS modules to be imported. As we are talking about Http the very first step is obviously.

<script src="node_modules/angular2/bundles/http.dev.js"></script>

But yes it is a good practice to provide HTTP_PROVIDERS in the bootstrap file because by using this way it is provided on a global level and is available to the whole project like this.

bootstrap(App, [
    HTTP_PROVIDERS, some_more_dependencies
]);

and the imports to be included are….

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';

Sometimes we need to provide Headers while consuming API’s for sending access_token and many more things which is done this way:

this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))

Now to RequestMethods: bascially we use GET, POST but there are some more options you can refer here…

We can use requestmethods as RequestMethod.method_name

There are some more options for the APIs but for now I have posted one example for POST request which will help you by using some important methods:

PostRequest(url,data) {
        this.headers = new Headers();
        this.headers.append("Content-Type", 'application/json');
        this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    return [{ status: res.status, json: res.json() }]
                }
            });
    }

you can refer here too for more info.

see also –

Update

import has been changed from

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';

to

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from '@angular/http';

Leave a Comment