4

Beginner's Guide to Angular: HTTP

 2 years ago
source link: https://code.tutsplus.com/tutorials/beginners-guide-to-angular-4-http--cms-29677
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In the previous tutorial, you saw how to implement routing in Angular web applications using Angular routing. 

In this tutorial, you'll learn how to communicate with web APIs and services from an Angular application using Angular HttpClient.

Angular HttpClient

You use the XMLHttpRequest(XHR) object to make server-side API calls from the browser. The XHR object makes it possible to update a portion of the web page without reloading the entire page. You can send and receive data from the server once the web page has loaded.

Angular HttpClient provides a wrapper for the XHR object, making it easier to make API calls from the Angular application. 

From the official documentation:

With HttpClient, @angular/common/http provides a simplified API for HTTP functionality for use with Angular applications, building on top of the XMLHttpRequest interface exposed by browsers. Additional benefits of HttpClient include testability support, strong typing of request and response objects, request and response interceptor support, and better error handling via apis based on Observables.

Getting Started

You'll start by cloning the source code from the first part of the tutorial series.

git clone https://github.com/royagasthyan/AngularComponent.git

Once you have the source code, navigate to the project directory and install the required dependencies.

cd AngularComponent
npm install

After the dependencies have been installed, start the application by typing the following command:

ng serve

You should have the application running on http://localhost:4200/.

In order to use the HttpClient module in your Angular application, you need to import it first in your app.module.ts file.

From the project directory, navigate to src/app/app.module.ts. In the app.module.ts file, import the HttpClientModule.

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

Include the HttpClientModule under the imports section.

imports: [
BrowserModule,
FormsModule,
HttpClientModule
]

Here is how the app.module.ts file looks:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CalcComponent } from './calc/calc.component'
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
CalcComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Now you will be able to use the HttpClientModule across the Angular application by importing it in the particular Angular component.

Creating the Angular Component

Let's start by creating the Angular component. Create a folder called get-data inside the src/app folder. Create a file called get-data.component.ts and add the following code:

import { Component } from '@angular/core';
@Component({
selector: 'get-data',
templateUrl: 'get-data.component.html',
styleUrls: ['get-data.component.css']
})
export class GetDataComponent {
constructor(){
}
}

Create a file called get-data.component.html which would serve as a template file for the get-data component. Add the following code for the get-data.component.html file:

<h3>
Get Data Component
</h3>

Import the GetDataComponent in the src/app/app.module.ts file.

import { GetDataComponent } from './get-data/get-data.component';

 Add the GetDataComponent to the ngModule in the app.module.ts

declarations: [
AppComponent,
CalcComponent,
GetDataComponent
]

Here is how the modified app.module.ts file looks:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CalcComponent } from './calc/calc.component';
import { GetDataComponent } from './get-data/get-data.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
CalcComponent,
GetDataComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Add the get-data component selector to the app.component.html file. Here is how it looks:

<div style="text-align:center">
<get-data></get-data>
</div>

Save the above changes and start the server. You will be able to view the get-data component displayed when the application loads.

Get Data Component
Get Data ComponentGet Data Component

Using the Angular HttpClient Module 

You'll be using the HttpClient module to make API calls. Let's create a separate file to create an Angular service for making the API call. Create a file called get-data.service.ts file. Add the following code to the get-data.service.ts file:

import { Injectable } from '@angular/core';
@Injectable()
export class GetDataService {
constructor() {
}
}

Import the HttpClient module to the above GetDataService.

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

Initialize the HttpClient in the GetDataService constructor.

constructor(private http: HttpClient) {
}

Create a method called call_api to make a GET API call in the GetDataService file. You'll make use of a word synonym finder API to make the API call. Here is how the call_api method looks:

call_api(term) {
return this.http.get(this.url + term);
}

Here is how the get-data.service.ts file looks:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class GetDataService {
url: string
constructor(private http: HttpClient) {
}
call_api(term) {
return this.http.get(this.url + term);
}
}

As seen in the above GetDataService class, the call_api method returns an observable to which you can subscribe from the GetDataComponent.

To subscribe from the GetDataComponent's constructor, you need to import the GetDataService in the GetDataComponent.

import { GetDataService } from './get-data.service';

Define the GetDataService as GetDataComponent's provider.

@Component({
selector: 'get-data',
templateUrl: 'get-data.component.html',
styleUrls: ['get-data.component.css'],
providers:[ GetDataService ]
})

Let's subscribe from the GetDataComponent's constructor method. 

constructor(private dataService: GetDataService){
this.dataService.call_api('hello').subscribe(response => {
console.log('Response is ', response);
})
}

Here is how the get-data.component.ts file looks:

import { Component } from '@angular/core';
import { GetDataService } from './get-data.service';
@Component({
selector: 'get-data',
templateUrl: 'get-data.component.html',
styleUrls: ['get-data.component.css'],
providers:[ GetDataService ]
})
export class GetDataComponent {
constructor(private dataService: GetDataService){
this.dataService.call_api('hello').subscribe(response => {
console.log('Response is ', response);
})
}
}

Save the above changes and restart the server. You will be able to see the result logged in the browser console.

In the above code, you saw how to make a GET API request using the Angular HttpClient.

To make a POST request, you need to make use of the http.post method.

this.http.post(url, {key : value});

As seen in the above code, you need to provide the API post URL and the data to be posted as the second parameter.

Advertisement

Handling Errors While Making API Calls

Whenever you make an API call, there is an equal possibility of encountering an error. In order to handle errors when making an API call, you need to add an error handler to the subscribe method along with the response handler.

Here is how the modified code from the GetDataComponent looks: 

constructor(private dataService: GetDataService){
this.dataService.call_api('hello').subscribe(response => {
console.log('Response is ', response);
}, err => {
console.log('Something went wrong ', err);
})
}

Modify the url variable in the get-data.service.ts file to create a non-existent URL which would cause an error when making the API call.

Save the above changes and restart the server. Check the browser console and you will have the error handler method called and the error logged.

The error object contains all details about the error such as the error code, error message, etc. It gives a deeper insight into what went wrong with the API call. Here is how the browser console log looks:

Error Handler Angular HttpClientError Handler Angular HttpClientError Handler Angular HttpClient

As seen in the above console log, all error details can be obtained from the error object.

Wrapping It Up

In this tutorial, you saw how to make use of the Angular HttpClientModule to make API calls. You learnt how to import the HttpClientModule for making the GET and POST request to the server APIs. You saw how to handle errors when making an API call.

How was your experience trying to learn how to make API calls using Angular HttpClientModule? Do let us know your thoughts in the comments below.

Source code from this tutorial is available on GitHub.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK