Angular HttpClient

HttpClient

One of the important topic for Frontend development.
We need to get information from server and draw, or post data to server to update data.
Angular provide httpclient to access server.

Jsonp, Http

Jsonp, Http in ‘@angular/http’ is deprecated. Use HttpClient

Test Server

For test, preparing server side app is a bit troublesome.
“jsonserver”(github) is easy solution to prepare json response api test.

Install

npm install json-server --save-dev

Add script command to package.json to run command easily.

Prepare json file to create response

data.json

{
  "name": {
    "Name": "Taro"
  },
  "list": [
      {
        "name": "Taro",
        "age": 25
      },
      {
        "name": "Santa",
        "age": 55
      }
  ]
}

In this example, json-server provides 2 apis
http://localhost:3004/name
http://localhost:3004/list

The response is application/json.

Simple Example

app.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { SimplehttpComponent } from './simplehttp.component';

@NgModule({
  imports: [
    CommonModule,
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  declarations: [
    SimplehttpComponent,
  ],
  bootstrap: [
    SimplehttpComponent
  ]
})
export class AppModule { }

simplehttp.component.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <form>
      <label for="name">Name : </label>
      <input id="name" name="name" type="text" &#91;(ngModel)&#93;="name"/>
      <input type="button" (click)="onclick()" value="Submit"/>
    </form>
    <div>{{result}}</div>
  `
})
export class SimplehttpComponent {
  name = '';
  result = '';

  constructor(private http: HttpClient) {}

  onclick() {
    this.http.get('http://localhost:3004/name', {params: {name: this.name},
    responseType: 'text'})
      .subscribe(response => {
        this.result = response;
      }, error => {
        this.result = `Failed : ${error.statusText}`;
      });
  }
}

Define Type

We can use type definition for response.
Prepare data class and automatically wrap from response, if response was wrong, of course, error has happens.

In this example, we use same json file. And we get following information from server

{"name": {
    "Name": "Taro"
  }
}

person.ts

export class Person {
  name: string;
  age: number;
}

simplehttptype.component.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

interface Person {
  Name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <form>
      <label for="name">Name : </label>
      <input id="name" name="name" type="text" &#91;(ngModel)&#93;="name"/>
      <input type="button" (click)="onclick()" value="Submit"/>
    </form>
    <div>{{result}}</div>
  `
})
export class SimplehttpTypeComponent {
  name = '';
  result = '';

  constructor(private http: HttpClient) {}

  onclick() {
    this.http.get<Person>('http://localhost:3004/name', {params: {name: this.name}})
      .subscribe(response => {
        console.log(response);
        this.result = response.Name;
      }, error => {
        this.result = `Failed : ${error.statusText}`;
      });
  }
}