Angular Http Request – 4

Modul ini akan membahas penggunaan types pada response data. Langkah ini optional namun disarankan karena dapat memperjelas intent dari code, dan berguna untuk IDE yang support auto completion.

Pertama kita buat interface. Buat file post.model.ts, lalu tambahkan code berikut

export interface Post{
    title: string; 
    content: string;
    id?: string;
}

Kita gunakan inteface diatas untuk mengatur types dari response data dengan cara <> type casting. Untuk jelasnya lihat contoh dibawah.

Contoh kita gunakan pada fetchPosts() method.

  private fetchPosts(){
    this.http
      .get<{ [key: string]: Post }>(


    //code goes here

    );
  }

Casting ini dapat dilakukan pada method request lainnya misalnya post.

  onCreatePost(postData: Post) {
    this.http
    .post<{ name: string }>(

      //code goes here

    );
  }

Berikut code lengkap dari app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators'; 

import { Post } from './post.model'; //import interface post model

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  loadedPosts = [];

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.fetchPosts();
  }

  //modifikasi types dari post data menggunakan interface
  onCreatePost(postData: Post) {
    this.http
    .post<{ name: string }>('https://angular03-f9c9b-default-rtdb.firebaseio.com/posts.json', postData).subscribe(
      responseData =>{
        console.log(responseData);
      }
    );
  }

  onFetchPosts() {
    this.fetchPosts();
  }

  onClearPosts() {
  }

  private fetchPosts(){
    this.http
      .get<{ [key: string]: Post }>('https://angular03-f9c9b-default-rtdb.firebaseio.com/posts.json')
      .pipe( map (responseData =>{ //proses transform data dari javascript object menjadi array.
        const postArr : Post[] = [];
        for (const key in responseData){
          if (responseData.hasOwnProperty(key)){
            postArr.push({...responseData[key], id: key});
          }
        }
        return postArr;
      }))
      .subscribe( posts =>{
        console.log(posts);
      }
    );
  }
}

Sharing is caring:

Leave a Comment