Angular 2 CRUD application using Nodejs

HTTP requests are very crucial and much needed in any modern front-end application and Angular 2 does this job very effortlessly. Angular 2 comes with its own HTTP library. Here, we will create Angular 2 CRUD application using Nodejs.

We will use Nodejs to create our REST API and we will use Angular 2’s  HTTP library to make HTTP requests with the help of Observables. In this article, We will make a list of user’s and we will create functionality to Update/ Remove the user from the list of users.

For this article, I am not sharing the code for REST API, You will find REST API code into the .zip file When you will download the code.

The final outcome of this article shown below in Image.

Angular 2 CRUD application using Nodejs demo

     Download

 




 

1. Angular 2 HTTP library

=> First take a look into Angular 2 HTTP library before creating our angular 2 CRUD application. Let’s understand what each request does and arguments required to it. Angular 2 HTTP library have different types of requests listed below,

  1. Request : 
    • request(url: string | Request, options?: RequestOptionsArgs): Observable<Response>;
    • The first argument is a URL and the second argument is optional which can be anything.
    • Can perform any type of request.
  2. get
    • get(url: string, options?: RequestOptionsArgs): Observable<Response>;
    • The first argument is a URL and the second argument is optional which can be anything .
    • Performs a request with get HTTP method.
  3. post
    •  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
    • The first argument is a URL and the second argument is optional which can be anything.
    • Performs a request with post HTTP method.
  4. put
    • put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
    • The first argument is a URL and the second argument is optional which can be anything.
    • Performs a request with put HTTP method.
  5. delete
    • delete(url: string, options?: RequestOptionsArgs): Observable<Response>;
    • The first argument is a URL and the second argument is optional which can be anything.
    • Performs a request with delete HTTP method.
  6. patch
    • patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;
    • The first argument is a URL and the second argument is optional which can be anything.
    • Performs a request with patch HTTP method.
  7. head
    • head(url: string, options?: RequestOptionsArgs): Observable<Response>;
    • The first argument is a URL and the second argument is optional which can be anything.
    • Performs a request with head HTTP method.

2. Setting up our Application

Let’s use Angular CLI to setup our application. If you don’t have Angular CLI installed on your machine run the below command to install it globally.
npm install -g angular-cli
After Angular CLI installation,to create a new Angular project Run below command. This command will create all the necessary files, download all the required external dependencies and do all of the setup work for us.

 

ng new AppName

 

3. Angular 2 CRUD application using Nodejs

=> Till now we understood Angular’s HTTP library and how many methods it has and Now let’s create angular service for our application.

=> In this service, we will implement methods to get a list of users, update a single user, add a user to the list and delete a user from the list. Before going any further let’s take a look at the app.module.ts file,

app.module.ts:

=> Now if you have notice, We have included three more modules into import array HttpClientModule, FormSupportingModule, and ServicesModule. Let’s understand why we need these modules,

1. HttpClientModule =>  If your application uses HTTP library, then you will have import this module.

2. FormSupportingModule => As the name of the module reads, you will add the all the form related module here.

3. ServicesModule => In this module, you will register the all the here.

4. Adding Services Module and General App supporting modules

=> In the last section, we understood that we will create two more modules i.e. FormSupportingModule, and ServicesModule.

=> To create FormSupportingModule, you will create a separate folder named as /modules inside the /app folder. Now make sure you are into the /modules folder, and run the below command,
ng generate module form-supporting

=> Now the above command will create form-supporting.module.ts under /form-supporting folder, in which we will register our Form modules. So open the form-supporting.module.ts and below code into it,

form-supporting.module.ts :

=> We will create a module named as services and all of our services will go under /services folder. The Services Module will add those services to our application.

=> So next time when you create any new service you don’t have to touch the app.moudle.ts file, Just add into service.module.ts file and you are done.

=> To create a service module run below command and add the below code into it,
ng generate module services

services.module.ts:

=> Here we will have two service forms.service.ts and http.service.ts. Each service has it’s own agenda, here FormService will help you when you create the Form using which you will add/update user details.

=> HttpService will hold the HTTP methods, which will be consumed by our AppComponent class. So let’s create these two services, to create them we will use below Angular CLI commands (make sure you are inside the /services folder),

  1. For form.services.ts file, Execute: ng generate service form
  2. For http.services.ts file, Execute: ng generate service http

service.modules.ts:

Explanation:

  1. When you create an Angular application on a big scale, it recommended to keep your application modular. So I have kept my habit to keep all of my Angular application modular.
  2. You can write above code in Component class without any doubt, but for the sake of modularity, I have kept this code in separate file.

=> Let’s take a look at HTTP service where we will use Angular’s HTTP library to make HTTP calls,
http.service.ts:

Explanation:

  1. We have imported all the interfaces from the folder called /interfaces. Just to save the length of this article, we won’t talk much about it. You will get all the interfaces when you download the code.
  2. To access the HTTP library, you will have to create an instance of it and then you can call an appropriate method on that created instance.
  3. As you can see here we have total 4 methods, every method name is self-explanatory. So just by looking at this code, you will get the purpose of each method.
  4. Here each method returns an observable of some specific interface, These Observables will be consumed in your component class.

5. Add a New user (Creating a POST HTTP Request)

=> In this application, we will have total three form fields i.e. username, email, and country. We have already created Service which holds the instance of the Form.

=> So we will use FormService service and complete our form by which we can add the new user details in our database. Open the app.component.html file and add the below markup.

=> The below code is very straightforward to understand, we have created a very basic Angular form. Also, we have added error message as well.

app.component.html:

=> Now the above markup will have you the have nice and simple form to add a user. But to make it work you have to write some code in AppComponent class. Now open your app.component.ts and add the below code,

 app.component.ts:

Explanation:

Let’s understand each line one by one,

  1. First, we have imported the FormService and HttpService services respectively then we have imported all the interfaces.
  2. Then we have three properties in our  AppComponent class as shown below,
    1. title: Needs no explanation!
    2. usersList: This array of objects having User as an interface, each object would represent a single user detail.
    3. userForm: This property will hold the instance of a Form.
  3. In constructor() method, you will use FormService to get the instance of a Form. Leave the ngOnInit() we will use it later.
  4. On the click of submit() method, you will call addNewUser() method. The addNewUser() method will basically consume the HttpService.
  5. The addUser() method is defined inside HttpService, in which you will pass the value of the form.
  6. After getting a response from the server, you will push the details inside the userList array.

6. Getting the list of users (Creating a GET HTTP Request)

=> Now that you have added a new user in your database, let’s fetch all those users and display them. The first step would be to write a markup in order to display the list of users.

=> In the below MarkUp, we have used *ngFor to iterate the users from the userList property, that’s all happening there.

app.component.html:

=> In the last section, we left ngOnInit() method blank. Here we will use it and we will consume the HttpService as usual to fetch the users stored in the database.

=> This will be a basic GET request which will fetch all users. Open the app.component.ts and all the below code,

app.compoent.ts:

Explanation:

  1. In ngOnInit() method, we have called getUsers() method of AppComponent class.
  2. The getUsers() method will consume the HttpService and return all the users stored in the database.

7. Deleting an existing user (Creating a DELETE HTTP Request)

=> Here, we will add a button (let’s say X) to each row of the list to delete a particular user from the list. Whenever the user clicks on delete button we will make DELETE HTTP request to the server.

=> Behind the scene, our API will remove that user from the database. Also, we will remove that user from the userList property of  AppComponent class.

Open the app.component.html replace the code for rendering the list view by this code,

app.component.html:

Explanation:

In the below code,

  1. When users click on X button we will call deleteUser() method  which is defined inside AppComponent class.
  2. In the deleteUser() method we will pass the id of the user and based on this id user will be deleted from the list and from the databse as well.

=> Now we will write the rest of code required to perform the delete operation. Open the app.component.ts file and the below method,

Explanation:

  1. The first thing we will do is, consume the deleteUser() method from HttpService. This will delete call the DELETE HTTP request, which will delete the user from the database.
  2. Once response received from the server, we will remove the user from the userList property of the AppComponent class.

8. Updating an existing user (Creating a PUT HTTP Request)

=> Building this part involves the two important steps, First selecting and highlighting user from the rendered List. Then calling a function to update the select, which eventually make the UPDATE HTTP request.

=> I have divided this part into two small parts, In the first part we will select and highlight the clicked user from the list of the user. In the second part, we will make an UPDATE HTTP request.

1. Highlighting the user from the list

In this part, we will mainly do three things,

  1. We will highlight the selected user from the list.
  2. We will update Form fields based on user selected from the list.
  3. Also, we will hide the Add User button and we will show the Update Button.

=> We have a separate article for highlighting a selected row in angular 2, I suggest you to read that article once if you don’t know how to do that. Open the app.component.html and replace the code for rendering the list view by this code,

app.component.html:

Explanation:

In the above markup, the two highlighted lines are doing trick for us.

  1. When we will click the list, the selectedUser() method will be triggred and this method will update the Form fields.
  2. isSelected() return boolean and based on that class .active will be applied to the li.

=> Now let’s write code inside the AppComponent class and the complete these features, Open the app.component.ts file and below property into it. The below property will hold the id of selected user from the list.

app.component.ts:

=> Now based on the above property we will show and hide the Update and Add User Button. So to do that, replace the Markup for the submit button by below markup.

=> In the below markup, the Buttons will hide/show based on selectedUserId property.

But to make this all happen, we have to write code inside the AppComponent class, Open the app.component.ts file add the two methods shown below,

app.component.ts:

Explanation:

  1. The selectedUser() method will update selectedUserId property and it will update values of form controls as well.
  2. isSelected() method will check if the selected user’s id equals to the selectedUserId property and based on this it returns a boolean value.

2. Making an HTTP request

=> Now the last piece of the puzzle is making HTTP calls to update the record in the database. When you will select any user from the list the update button will show up.

=> On the click of that button submit() method will get triggered, so we will add the code to make the HTTP request in that method only. Now Open the app.component.ts file and replace the code of submit() method by the below code,

app.component.ts:

Explanation:

In the below code,

The first thing would be to call updateUser() or addNewUser() based on selectedUserId property.

Then inside the updateUser() method two things are happening first is we are making an HTTP call to update the record of user and second we will update the userList as well for that particular id.

Conclusion

In this article we understood, Angular 2 HTTP library and it’s methods and we created a basic CRUD application using Angular 2. If you have any questions or doubts let me know in below comment box, So that’s the end of this long article.

Also, If you find this article useful the do share with others.