How to call an API from Angular 7?

In my earlier blog, I have explained How to create a static website in Angular 7? In this blog, we will see How to call an API from Angular 7.
To Call an API from Angular we need HttpClientModule which is available in '@angular/common/http'.

This HttpClientModule should be imported in app.module.ts file. (Root App module)

import {HttpClientModule} from '@angular/common/http'

Now we have to inject HttpClient in the component.ts file for which we have to call API.

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

What is HttpClient?


We all know that Angular is client side framework for data rendering. To communicate with backend services we will use HTTP protocol.

HttpClient is available in '@angular/common/http' and it offers a way to communicate with an API.

To Call API from Angular follow below steps

As you can see, HttpClientModule is imported at the top section in the app.module.ts file and then added in imports array available in root module file.

Below is the app.module.ts file source code.


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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewsComponent } from './pages/news/news.component';
import {HttpClientModule} from '@angular/common/http'
import { from } from 'rxjs';

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

I have created a news component, so injected HttpClient and then created an object of HttpClient in constructor.

Object of HttpClient is client as shown in below code.

Next, within ngOnInit() method, we have define a const variable which will have the URL of the API.

As we have to fetch and show data on page so we have used HttpClient.get() to call subscribe() method which fetch the records in a variable called response.


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

@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {

constructor(private client:HttpClient) { }

ngOnInit() {
const url="<API URL>";
this.client.get(url)
.subscribe(response=>
{
console.log(response);
}, err=>
{
console.log("Service Not Found");
})
}

}


Once we have fetched the data from the API, we can either check on console or we can store the response in a variable and then we can apply *ngFor on component's html file to present data for users.

If you like this blog, then please share this on social media and comment down below to give your feedback.


Comments

Popular

What is Web API? When should we use in our projects?