Skip to main content

Everything You Need to Know About HTTP in Angular and Making HTTP Request in Angular

 

Before we start sending requests, it's important to understand the anatomy of an HTTP request


because a HTTP request is made up of a couple of core parts which we'll all have a look at in this module


here when it comes to configuring them when sending a request.


The most important part about a request of course is the URL you are sending the request to,


that's also called the API endpoint and it is something like yourdomain.com/posts/1


for example, the exact path here of course depends on the API you're interacting with.


However, when communicating with a RESTful API, it's not just about the URL but also about the


HTTP verb you're using, something like post, get, put. This defines which kind of request you want to


send


to that endpoint, do you want to store a new data?


Do you want to fetch data?


Do you want to replace existing data?


The HTTP verb makes that clear but it always depends on the API you're working with, which endpoints and


which verbs for these endpoints are available,


so the official docs for the API is always the place to go, unless you're of course writing your own API


in which case you of course know which endpoint supports which operations.


Now, when we're sending a request, it's nice to know where and how to send it to that place but you often


also need to set additional metadata, the so-called headers of a request.


Now these are kind of optional or to be precise, some default headers will be appended to a request for


you by the browser and by Angular but you can also append your own headers and that is therefore also


something we'll have a look at.


Now last but not least, for some HTTP verbs,


you can also add a body to your request,


that's the core data that is attached to a request.


For example if you're sending a post request to create a new piece of data on the server, well then of


course you should attach the information about that piece of data to your request and you would do


that in the request body.


Therefore a request body can be set on post, put and patch requests which are requests that do alter


data on the server by adding or replacing it.


Now that's the general anatomy of a HTTP request,


let's now have a look at how Angular helps us with writing or with creating such requests,


how we can work with them, how we can work with the response and what else Angular has to offer.



Step 1. First Import HttpClientModule module in app.modules.ts  from @angular/common/http

Step 2. Add this HttpClientModule in imports : [] array.


Now you add that HttpClient module here in your imports array, just like that.

This now unlocks the client Angular offers in your whole project and with that, we can now start sending requests in our app component here.


In there, we now just need to inject our HttpClient and I'll store it in a property which I just


name HTTP and it's the HttpClient which you need to import from


@angular/common/http,


so make sure to add this import at the top of your path.


Now with it imported, we can use it to send HTTP requests


Step 3: in constructor we have to inject httpClient like this

constructor (private http: HttpClient){}


Step 4: Now injected http refrence we can use to call http methods in respective method. 

like 

onCreatePost(postData: {title: string; content: string})
{
    this.http.post('')
}

post(): this post method will take couple of arguments like url at which you want to send this request but this post method not only required url but it also need body. Means this post need 2 arguments and second argument is request body that could be our request data (means postData ). 

Note: If we not subscribe then this method will not send any request so we have to subscribe this method. 

it gives us an observable

that wraps your request and to get access to the response, you have to call

subscribe here and this will then be your response data actually because Angular, the HttpClient

I should say, will do even more than just giving you the response, it will automatically extract the

data attached to the response,

so the response body and give you that, though you also have ways of accessing the full response as you


will learn later.

So for now, let's simply console log that response data to get a feeling for whether that works and what

we get here.







Get Method

Like if we wish to get some data in angular we have to create a method like 

private fetchData()
{
    this.http.get('url').subscribe(posts=>{
        console.log(posts);
    })
}



Now here we can get data in different formate so we have to transform data inside the subscribe that would generally not a problem. But it is a good practice to use observable operator because its simply allow us to write cleaner code with different steps. Like we have used pipe and map operator to transform data. before reaching to subscribe method. 

we funnel our data through that can easily be swapped or adjusted, so that you have a clean subscribe

function here and have other steps that focus on other parts. Therefore

here before we subscribe, we can now call pipe because pipe as you learned is a method that allows you

to funnel your observable data through multiple operators before they reach the subscribe method.






Comments

Popular posts from this blog

How do I change the time zone of my Amazon RDS database instance?

As we know bydefault time in the format of UTC in mysql.We can set local time zone to our AWS RDS Instance for our application. or any other time zone prefared Cloud Based Website Hosting Service Provider Steps 1: Go to Services and Select RDS Now to change time zone we have to change "Parameter Group" in left side that is associated with DB instance first we can check default Parameter Group for our instance is Parameter group default.mysql5.7  ( in-sync ) like this. So we have to change the time zone in this Parameter Group.  now open that parameter group (default.mysql5.7)  and click on edit parameter. then search for time_zone (because we want to change it.) then we have to change time_zone only by default it is engine-default (that is utc)  we have to select Asia/Calcutta.  More information we can ref.  https://aws.amazon.com/premiumsupport/knowledge-center/rds-change-time-zone/

Changing the Time Zone on Amazon Linux Ec2 Instance

Amazon Linux instances are set to the UTC (Coordinated Universal Time) time zone by default, but you may wish to change the time on an instance to the local time or to another time zone in your network. Important These procedures are intended for use with Amazon Linux. For more information about other distributions, see their specific documentation. To change the time zone on an instance Identify the time zone to use on the instance. The  /usr/share/zoneinfo  directory contains a hierarchy of time zone data files. Browse the directory structure at that location to find a file for your time zone. [ec2-user ~]$ ls /usr/share/zoneinfo Africa Chile GB Indian Mideast posixrules US America CST6CDT GB-Eire Iran MST PRC UTC Antarctica Cuba GMT iso3166.tab MST7MDT PST8PDT WET Arctic EET GMT0 Israel Navajo right W-SU ... Some of the entries at this location are directo

Digital Marketing

What actually is Digital Marketing? This post will help you understand the insights of Digital Marketing What is Digital Marketing? Digital Marketing is an integral part of the overall marketing strategies of any business. It basically covers the advertisement of products/services/business/brand via digital channels. The digital channels could be of any type like websites, search engines, social media, emails, SMS, and MMS. In case if you're using all these digital channels for the marketing, make sure to have all the statistics & workflow of your campaigns via marketing automation. What are the types of digital marketing? Well, there are 6 core digital marketing types: Search Engine Optimization (SEO) : Search Engine Optimization is nothing but a long-term process of improving your website rankings on search engine results pages (SERPs), which in turn has a wide range of tactics & strategies to implement. Although there is no specific method or a  spec