How to Consum REST API from Angular 2/4 Web Application


Making POST request to fetch the data from API

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { contentHeaders } from '../common/headers';
import { Router } from '@angular/router';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {

    constructor(public router: Router, private _http: Http) { }

    registerUser(inputData: string) {
        let body = JSON.stringify({ inputData });

        this._http.post('http://localhost:3000/api/<endpoint>', body, { headers: contentHeaders })
            .subscribe(
            response => {
               console.log(response.json());
                this.router.navigate(['home']);
            },
            error => {
                alert(error.text());
                console.log(error.text());
            }
            );
    }

}


Content Headers

import { Headers } from '@angular/http';

export const contentHeaders = new Headers();
contentHeaders.append('Accept', 'application/json');
contentHeaders.append('Content-Type', 'application/json');

contentHeaders.append('Access-Control-Allow-Origin', '*');

Comments

Popular posts from this blog

Angular 2/4 Content Translation using ngx-translate

Angular 2/4 NGX Translate Complete Implementation with Example

Angular 2/4 and TypeScript Dynamically Access/Append HTML Nodes