ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular HttpClient Tutorial & Example

In this Angular HttpClient Tutorial & Examples guide, we show you how to use HttpClient to make HTTP requests like GET & POST, etc. to the back end server. The Angular HTTP client module is introduced in the Angular 4.3. This new API is available in package @angular/common/http. It replaces the older HttpModule. The HTTP Client makes use of the RxJs Observables. The Response from the HttpClient is observable, hence it needs to be Subscribed. We will learn all these in this Tutorial.

Using Angular HttpClient

The HttpClient is a separate model in Angular and is available under the @angular/common/http package. The following steps show you how to use the HttpClient in an Angular app.

Import HttpClient Module in Root Module

We need to import it into our root module app.module. Also, we need to add it to the imports metadata array.

                              

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
 
@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }
                            
                        

Import Required Module in Component/Service

Then you should import HttpClient the @angular/common/http in the component or service.

                              

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

Inject HttpClient service

Inject the HttpClient service in the constructor.

                              

constructor(public http: HttpClient) {
}
 
                            
                        

Call the HttpClient.Get method

Use HttpClient.Get method to send an HTTP Request. The request is sent when we Subscribe to the get() method. When the response arrives map it the desired object and display the result.

                              
 
public getData() {
  this.HttpClient.get<any[]>(this.baseUrl+'users/'+this.userName+'/repos')
           .subscribe(data => {
               this.repos= data;
           },
           error => {
           }
  );
}
 
                            
                        

What is Observable?

The Angular HTTPClientmakes use of observable. Hence it is important to understand the basics of it

Observable help us to manage async data. You can think of Observables as an array of items, which arrive asynchronously over time.

The observables implement the observer design pattern, where observables maintain a list of dependents. We call these dependents as observers. The observable notifies them automatically of any state changes, usually by calling one of their methods.

Observer subscribes to an Observable. The observer reacts when the value of the Observable changes. An Observable can have multiple subscribers and all the subscribers are notified when the state of the Observable changes.

When an Observer subscribes to an observable, it needs to pass (optional) the three callbacks.next() , error() & complete(). The observable invokes the next() callback, when it receives an value. When the observable completes it invokes the complete() callback. And when the error occurs it invokes the error() callback with details of error and subscriber finishes.

The Observables are used extensively in Angular. The new HTTPClient Module and Event system are all Observable based.

The Observables are proposed feature for the next version of Javascript. The Angular uses a Third-party library called Reactive Extensions or RxJs to implement the Observables. You can learn about RxJs from these RxJx tutorials

Observables Operators

Operators are methods that operate on an Observable and return a new observable. Each Operator modifies the value it receives. These operators are applied one after the other in a chain.

The RxJs provides several Operators, which allows you to filter, select, transform, combine and compose Observables. Examples of Operators are map , filter , take , merge, etc

How to use RxJs

The RxJs is a very large library. Hence Angular exposes a stripped-down version of Observables. You can import it using the following import statement

                              

import { Observable } from 'rxjs';
 
                            
                        

The above import imports only the necessary features. It does not include any of the Operators.

To use observables operators, you need to import them. The following code imports the map & catchError operators.

                              

import { map, catchError } from 'rxjs/operators';
                            
                        

HTTP GET

The HttpClient.get sends the HTTP Get Request to the API endpoint and parses the returned result to the desired type. By default, the body of the response is parsed as JSON. If you want any other type, then you need to specify explicitly using the observe & responseType options.

You can read more about Angular HTTP Get

Syntax

                              


 get(url: string, 
      options: {
          headers?: HttpHeaders | { [header: string]: string | string[]; };
          params?: HttpParams | { [param: string]: string | string[]; };
          observe?: "body|events|response|";
          responseType: "arraybuffer|json|blob|text";
          reportProgress?: boolean; 
          withCredentials?: boolean;}
     ): Observable<>
 
                            
                        

Options

under the options, we have several configuration options, which we can use to configure the request.

headers It allows you to add HTTP headers to the outgoing requests.

observe The HttpClient.get method returns the body of the response parsed as JSON (or type specified by the responseType). Sometimes you may need to read the entire response along with the headers and status codes. To do this you can set the observe property to the response.

The allowed options are

  • a response which returns the entire response
  • body which returns only the body
  • events which return the response with events.
  • params Allows us to Add the URL parameters or Get Parameters to the Get Request

    reportProgress This is a boolean property. Set this to true, if you want to get notified of the progress of the Get Request. This is a pretty useful feature when you have a large amount of data to download (or upload) and you want the user to notify of the progress.

    responseType Json is the default response type. In case you want a different type of response, then you need to use this parameter. The Allowed Options are arraybuffer ,blob ,JSON , and text.

    withCredentials It is of boolean type. If the value is true then HttpClient.get will request data with credentials (cookies)

    HTTP Post

    The HttpClient.post() sends the HTTP POST request to the endpoint. Similar to the get(), we need to subscribe to the post() method to send the request. The post method parsed the body of the response as JSON and returns it. This is the default behavior. If you want any other type, then you need to specify explicitly using the observe & responseType options.

    You can read Angular HTTP Post

    The syntax of the HTTP Post is similar to the HTTP Get.

                                  
    
    post(url: string, 
         body: any, 
         options: { 
            headers?: HttpHeaders | { [header: string]: string | string[]; }; 
            observe?: "body|events|response|"; 
            params?: HttpParams | { [param: string]: string | string[]; }; 
            reportProgress?: boolean; 
            responseType: "arraybuffer|json|blob|text"; 
            withCredentials?: boolean; 
         }
    ): Observable
                                
                            

    The following is an example of HTTP Post

                                  
    
    addPerson(person:Person): Observable<any> {
        const headers = { 'content-type': 'application/json'}  
        const body=JSON.stringify(person);
        this.http.post(this.baseURL + 'people', body,{'headers':headers , observe: 'response'})
          .subscribe(
           response=> {
                console.log("POST completed sucessfully. The response received "+response);
            },
            error => {
                console.log("Post failed with the errors");
            },
            () => {
                console.log("Post Completed");
            }
    }
     
     
                                
                            

    HTTP PUT

    The HttpClient.put() sends the HTTP PUT request to the endpoint. The syntax and usage are very similar to the HTTP POST method.

                                  
    
    put(url: string, 
         body: any, 
         options: { 
            headers?: HttpHeaders | { [header: string]: string | string[]; }; 
            observe?: "body|events|response|"; 
            params?: HttpParams | { [param: string]: string | string[]; }; 
            reportProgress?: boolean; 
            responseType: "arraybuffer|json|blob|text"; 
            withCredentials?: boolean; 
         }
    ): Observable
     
                                
                            

    HTTP PATCH

    The HttpClient.patch() sends the HTTP PATCH request to the endpoint. The syntax and usage are very similar to the HTTP POST method.

                                  
    
    patch(url: string, 
         body: any, 
         options: { 
            headers?: HttpHeaders | { [header: string]: string | string[]; }; 
            observe?: "body|events|response|"; 
            params?: HttpParams | { [param: string]: string | string[]; }; 
            reportProgress?: boolean; 
            responseType: "arraybuffer|json|blob|text"; 
            withCredentials?: boolean; 
         }
    ): Observable
                                
                            

    HTTP DELETE

    The HttpClient.delete() sends theHTTP DELETE request to the endpoint. The syntax and usage are very similar to the HTTP GET method.

                                  
     
    delete(url: string, 
          options: {
              headers?: HttpHeaders | { [header: string]: string | string[]; };
              params?: HttpParams | { [param: string]: string | string[]; };
              observe?: "body|events|response|";
              responseType: "arraybuffer|json|blob|text";
              reportProgress?: boolean; 
              withCredentials?: boolean;}
         ): Observable<>
     
                                
                            

    HttpClient Example

    Now, We have a basic understanding of HttpClient model & observables, let us build an HttpClient example app.

    Create a new Angular app

                                  
    
    ng new httpClient
     
                                
                            

    import HttpClientModule

    In the app,module.ts import the HttpClientModule module as shown below. We also add it to the imports array

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

    Component

    Now, open the app.component.ts and copy the following code.

                                  
     
    import { Component, OnInit } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
     
    export class Repos {
      id: string;
      name: string;
      html_url: string;
      description: string;
    }
     
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
    })
    export class AppComponent implements OnInit {
     
      userName: string = "tektutorialshub"
      baseURL: string = "https://api.github.com/";
      repos: Repos[];
     
      
      constructor(private http: HttpClient) {
      }
     
      ngOnInit() {
        this.getRepos()
      }
     
     
      public getRepos() {
     
        return this.http.get<Repos[]>(this.baseURL + 'users/' + this.userName + '/repos')
          .subscribe(
            (response) => {                           //Next callback
              console.log('response received')
              console.log(response);
              this.repos = response; 
            },
            (error) => {                              //Error callback
              console.error('Request failed with error')
              alert(error);
            },
            () => {                                   //Complete callback
              console.log('Request completed')
            })
      }
    }
     
                                
                            

    Import HTTPClient

    HTTPClient is a service, which is a major component of the HTTP Module. It contains methods like GET , POST , PUT etc. We need to import it.

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

    Repository Model

    The model to handle our data.

                                  
    
    export class Repos {
      id: string;
      name: string;
      html_url: string;
      description: string;
    }
     
                                
                            

    Inject HttpClient

    Inject the HttpClient service into the component. You can learn more about Dependency injection in Angular

                                  
    
    constructor(private http: HttpClient) {
    }
     
                                
                            

    Subscribe to HTTP Get

    The GetRepos method, we invoke the get() method of the HttpClient Service.

    The HttpClient.get method allows us to cast the returned response object to a type we require. We make use of that feature and supply the type for the returned value http.get <repos[]>

    The get() method returns an observable. Hence we subscribe to it.

                                  
    
    public getRepos() {
       return this.http.get<Repos[]>(this.baseURL + 'users/' + this.userName + '/repos')
          .subscribe(
     
                                
                            

    When we subscribe to any observable, we optionally pass the three callbacks. next() , error() & complete(). In this example we pass only two callbacks next() & error().

    Receive the Response

    We receive the data in the next() callback. By default, the Angular reads the body of the response as JSON and casts it to an object and returns it back. Hence we can use directly in our app.

                                  
    
    (response) => {                           //Next callback
        console.log('response received')
        console.log(response);
        this.repos = response; 
    },
     
                                
                            

    Handle the errors

    We handle the errors in error callback.

                                  
    
    (error) => {                              //Error callback
            console.error('Request failed with error')
            alert(error);
     },
     
                                
                            

    Template

    We handle the errors in error callback.

                                  
    
    <h1 class="heading"><strong>HTTPClient </strong> Example</h1>
     
     
    <table class='table'>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>HTML Url</th>
          <th>description</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let repo of repos;">
          <td>{{repo.id}}</td>
          <td>{{repo.name}}</td>
          <td>{{repo.html_url}}</td>
          <td>{{repo.description}}</td>
        </tr>
      </tbody>
    </table> 
     
    <pre>{{repos | json}}</pre>
     
                                
                            

    Finally, we display the list of GitHub Repos using the ngFor Directive

    Summary

    We learned how to create a simple HTTP Service in this tutorial. We also looked at the basics of Observables which is not extensively used in Angular

    You can download the source code from this link