Miyerkules, Disyembre 23, 2020

Angular Basic HTTP Post & Get Tutorial


Data is everything in a web app. Now I'll show you how to do a basic http requests on Angular 11.

For this exercise, we'll use typicode's json placeholder for our data.




To make our lives easier, we will create a reusable service called "dataHTTPService" service wrapper class.

First, we need the HttpClientModule module imported and referenced in the app.module.ts.

import { HttpClientModule } from "@angular/common/http";

It will have these two functions get and post request.

public sendGetRequest(url: string) {
    return this.httpClient.get(url);
  }
  
  public sendPostRequest(url: string, body: any) {
    const _headers = new HttpHeaders().set("Content-Type", "");

    return this.httpClient.post(this.REST_API_SERVER + url, body);
  }

Let's use the photos get request URL so we can display a list of thumbnails for our example.

jsonplaceholder.typicode.com/photos

We can now fetch data in our app module's OnInit function:

ngOnInit(): void {
    this.ds
      .sendGetRequest("http://jsonplaceholder.typicode.com/photos")
      .subscribe((data: any) => {
        console.log(data[0]);
      });
  }

Now you'll see our list of thumbnails:



Play with the StackBlits code.

Buy me a cup of coffee :)


Walang komento:

Mag-post ng isang Komento