Welcome to part-12 of Angular Basics series. In this part , we will learn to do HTTP requests in Angular.
The starting point can be taken from here.
We have a simple template driven form as the starting point in our project.
Now, we are going to use firebase in our project to store the backend data. Open the firebase console and click on Add Project button.
It will ask to give the project a name, which we can give any.
In the next screen disable google analytics and click on Create Project button.
It will create a New Project and we can click on the Continue button.
Here, click on Realtime Database and then Create Database button.
It asked me the location and i gave Singapore as it’s the closest.
In the next screen, it’s important to Start in Test mode.
In the next screen, we will get the url to send request to from our frontend.
Back in our Application, we should make sure that we have the HttpClientModule in app.module.ts file.
Now, we will use the HttpClient provided by angular to send the POST request to the firebase endpoint. Also notice that we have added posts.json at the end.
Make sure to import the HttpClient also in app.component.ts file.
Now, in localhost we can add Title and Content and click on Send Post and the post will be sent successfully as shown in network tab.
We can also see the post in firebase.
Now, we will check the request to get all the posts. We will create a fetchPosts function to get the posts and call it from ngOnInit and onFetchPosts in app.component.ts file.
Now, back in localhost we will get an object from firebase with our posts.
We need to transform this object for using in our project and for this we will use pipe operator with map function from angular.
Here, we are looping through the object using the for..in loop and creating a new array with objects.
Now, back in localhost our data is formatted well.
In typescript code we should have type of Http requests and for this we will first create a post.model.ts file inside the app folder. It is an interface with the model of data.
Next, we will use this model in our app.component.ts file to refer to type at various places.
Now, we will display the posts in our app and also show Loading when the data is getting fetched. So, in app.component.ts file add the variable for loadedPosts and isFetching.
Before the posts are been fetched, make the to isFetching true and when the posts are been fetched make it true and also the loadedPosts equal to the posts received.
Now, in the app.component.html file show the No posts available, only if the loadedPosts and isFetching is not true. We are also looping through the loadedPosts and showing them.
The Loading… text is also shown if isFetching is true.
Our main code for HTTP request is done and the loading indicator is also working. We will modify this code in the next part to use services.
This completes our post and you can find the code for the same in this github repo.