How to make HTTP requests in angular GET.POST.DELETE http methods

 How to make HTTP requests in angular 


Hello learner or visitor myself Anil in this i article i will discuss about how to make HTTP api calls in angular.

Required knowledge 

1.Basics of HTML
2.type script basics
3.understanding of HTTP protocals

http request in angular,GET,POST,PUT method in angular


Introduction to angular


Angular is a javaScript framework introduced by google .Actually this is open source full stack web application framework special developed for SPA(single page application).Angular provides many features and with the help of the this framework we can create not only web applications but also hybrid and native applications with the help of some other frameworks like IONIC ok let's move forward to the main topic i wil provide another article for ionic how we can use it to create hybrid and native applications.



What is HTTP ?

HTTP (Hypertext Transfer Mechanism) is a protocol for retrieving resources such as HTML documents. It is the foundation of any data interchange on the Internet, and it is a client-server protocol, meaning that requests are started by the recipient, which is commonly the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance, text, layout description, images, videos, scripts, and more.In angular implement http request are very easy.

What are the HTTP methods ?

There are total 6 methods of HTTP protocal let's discuss one by then you can get more clarity on that.

1.GET
2.POST
3.PUT
4.PATCH
4.DELETE


GET method


Using this method we can get the data according to the condition 

Syntax:

get.(URL,body).subscribe(data=>{
........
}}

Here in this method are the get request we are passing parameters like url,body and headers .this method is basically used to fetch the data from web server .

POST method

Using this method we can send data to the webserver .


Syntax:

post.(URL,body).subscribe(data=>{
........
}}


Here in this method we are passing headers and param to send post request with some data.this method is basically is used to create a new record in data base.

PUT method 

Using this method we can update a record available on data base this is similar method as  HTTP post method .


PUT(URL,body).subscribe(data=>{
........
}}


Here in this method we can update a record according to the condition .

DELETE method 

using this method we are deleting a record from the data using backend server endpoint .


DELETE(URL,body).subscribe(data=>{
........
}}

Sometimes we want to delete record from data base using backend api then we can use this HTTP DELETE method .



Let's implement these methods in angular one by one 


In angular make HTTP request are very easy in angular everything happens with help of in build libraries to implement HTTP in angular we can use HttpClientModule . First of all we have install the module inside root module inside app.module.ts file.


import { ErrorHandler, NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    HttpClientModule,
 
  ],
  providers: [

  ],
  bootstrap: [AppComponent]
})
export class AppModule {

}



Here we have added HttpClientModule to use all necessary methods inside angular . 


Next we are going to use http method inside application to make api calls.


GET request in angular 

first of all we are going to create one dummy angular app with this command 

ng new Applicationname

You can see a default angular application structure after firing this command.Now we are ready to implement HTTP methods .


we are going to generate one service here to implement all methods inside this shared service this alternatively known as Dependency Injection (DI).i will add another article for this topic .so coming to the point now we are going create a GET request from our service 

generate a service with command 

ng g s service name 

ng-new generation
g-generatea
s-service 
name-service name 


after firing this command we will get one service class like this or we can say a injectable class.



import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class Servicename {

    constructor(
        private httpService: HttpClient
    ) { }

    fetchdata(data): Observable<any> {
        const headers = new HttpHeaders({
            Authorixation:"accesstoken",
        });
        return this.httpService.GET(`api/userdata, data, headers);
    }
}




here inside this service we have instantiate http client to use the HTTP methods with a reference variable httpService.Then after this we are passing access token if the backend server is demanding then inside header like this .

const headers = new HttpHeaders({
            Authorixation:"accesstoken",
        });

Then we have to make the get request using the backend server api endpoint api/userdata .Ok so now method is ready to be subscribed wherever we want.

So let's move inside app.component.ts 

Inside this component we can use our service and it's methods by simply initializing it inside the constructor.



import { Component } from '@angular/core';
import { Service } from '......///service path";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewChecked {

  constructor(
    private Service: ServiceName,
  ) {
    this.service.getusers.subscribe((data) => {
     console.log(data);
    });
  }



we just need to subscribe the method here and after that it will take some time to make communication with backend server will do necessary calculation and then will return out request data to the Consumer.


POST request in angular 

We have to follow same process for POST method as we have done for GET method just need some small changes . first of all we are going to create one dummy angular app with this command 

ng new Applicationname

You can see a default angular application structure after firing this command.Now we are ready to implement HTTP methods .


we are going to generate one service here to implement all methods inside this shared service this alternatively known as Dependency Injection (DI).i will add another article for this topic .so coming to the point now we are going create a GET request from our service 

generate a service with command 

ng g s service name 

ng-new generation
g-generatea
s-service 
name-service name 


after firing this command we will get one service class like this or we can say a injectable class.



import { HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class Servicename {

    constructor(
        private httpService: HttpClient
    ) { }

    createuser(data): Observable<any> {
        const headers = new HttpHeaders({
            Authorixation:"accesstoken",
        });
        return this.httpService.post(`api/createUser, data, headers);
    }
}




here inside this service we have instantiate http client to use the HTTP methods with a reference variable httpService.Then after this we are passing access token if the backend server is demanding then inside header like this .

const headers = new HttpHeaders({
            Authorixation:"accesstoken",
        });

Then we have to make the get request using the backend server api endpoint api/userdata .Ok so now method is ready to be subscribed wherever we want.

So let's move inside app.component.ts 

Inside this component we can use our service and it's methods by simply initializing it inside the constructor.



import { Component } from '@angular/core';
import { Service } from '......///service path";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewChecked {

  constructor(
    private Service: ServiceName,
  ) {

let data={
USERid:"...."
}
    this.service.getusers.subscribe((data) => {
     console.log(data);
    });
  }



we just need to subscribe the method here and after that it will take some time to make communication with backend server will do necessary calculation and then will return out request data to the Consumer.

any query please comment below we will try to develop our contents according tot your feedback.






Post a Comment

Previous Post Next Post