Angular, HttpClient with test data from jsonplaceholder.typicode.com


Here we will check how to deal with http call in Angular. As a backend I will use jsonplaceholder.typicode.com service. How to setup simple project you can find here http://blog.michalszalkowski.com/java-script/angular-reactive-form-formcontrol-formgroup-validators/ FYI here you will find only small notes, more you can find in Angular Guide

app.component.ts

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

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

  private posts: any[];
  private url = "https://jsonplaceholder.typicode.com/posts";

  constructor(private http: HttpClient) {
    this.getPosts();
  }

  getPosts() {
    this.http.get(this.url)
      .subscribe((response: any[]) => {
        this.posts = response;
      });
  }

  createPost(input: HTMLInputElement) {
    this.http.post(this.url, JSON.stringify({post: input.title}))
      .subscribe((response: any) => {
        console.log(response)
      });
  }
}

this implementation will be quite ok if not one thing: OnInit interface, please fix code base on this

export class PostComponent implements OnInit {

  private posts: any[];
  private url = "https://jsonplaceholder.typicode.com/posts";

  constructor(private http: HttpClient) {
  }

  ngOnInit() {
    this.getPosts();
  }

app.component.html

<ul class="list-group">

  <li class="list-group-item">
    <input
      (keyup.enter)="createPost(title)" #title
      type="text" class="form-control">
  </li>

  <li
    *ngFor="let post of posts"
    class="list-group-item">{{post.id}} | {{post.title}}</li>

</ul>

please remember about adding HttpClientModule to app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { PostComponent } from './post/post.component';
import { HttpClientModule } from "@angular/common/http";


@NgModule({
  declarations: [
    AppComponent,
    PostComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }