In order to use the Http Client Module one must first import the Http Client Module in the app.module.ts file. To do so one can import the following into their app.module.ts file.
import { HttpClientModule } from '@angular/common/http';
From there one is able to add the HttpClientModule to the imports array. From there the Http Client Module can be used in any and all components who are listed in the declarations location of the app.module.ts file.
So here is a fictional scenario. We have a backend service running on localhost port 8080 and want to connect it to our Angular Front-End. So what are we to do? Are we to use Fetch or Axios like React or View? The short answer to this question: is yes. The long answer however is no. We will not be using axios or fetch in this part of the project. Instead we will be using the HttpClient Module that is installed when one installs @angular/core. This goes as such.
import { HttpClient } from '@angular/common/http';
From here I am able to use the Http Client Module in my app.component.ts file. Note do not forget to add the dependency into the constructor.
constructor(private http: HttpClient) { }
Finally one is able to use the Http Client Module. Like so.
import { Component, OnInIt } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Posts } from './posts.interface.ts'
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
export class AppComponent implements OnInIt {
constructor(private http: HttpClient) { }
this.http.get('/api/getBlogPosts').subscribe((res: any) => {
this.blogPosts = res['posts'];
One is then able to map the data in the HTML like we just did except this time with the backend service.
Post
{{ element.title }}
This should now look like so considering the data from our backend service.
Now we will transition into better Angular Practices: including using a service and interface.
---
This episode is sponsored by
· Anchor: The easiest way to make a podcast. https://anchor.fm/app
---
Send in a voice message: https://anchor.fm/javascript-news/message
Support this podcast: https://anchor.fm/javascript-news/support