How to consume an JSON REST api Server ? angular basic interview question
2 min readOct 11, 2024
Consume an api- is calling url of api over server and handling the response accordingly
In Angular we use http client module by injecting it into main module then creating a service or directly use component using http Client service.
Angular Version — 18
Node version LTS — 20.18.0
In Vanilla Java Script, We have axios and fetch for getting response. But in angular we have http service in http client module.
http.get<MyDataType>('/yourapiurl').subscribe(myData=> {
// process the myData.
});
Your full server url if you haven’t configured proxy.
Main module injection
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private server:string = 'https://api.example.com/';
constructor(private httpService: HttpClient) { }
getData<T>(url:string): Observable<T> {
return this.httpService.get<T>(this.server+url);
}
postData<T>(url,data:T): Observable<T> {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.httpService.post<T>(this.server+url,data, { headers });
}
}
<T> T represent the data type generic
You can use these methods in components
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
template: `
<div *ngIf="data">
<pre>{{ myData | json }}</pre>
</div>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
myData: any;
constructor(private apiService: ApiService) { }
ngOnInit(): void {
this.apiService.getData<any>().subscribe(
(response) => this.myData = response,
(error) => console.error('Error fetching data:', error)
);
}
addData(newData: any): void {
this.apiService.postData<any>(newData).subscribe(
(response) => console.log('Data added:', response),
(error) => console.error('Error adding data:', error)
);
}
}
…………………………………………………………………………………The End