Search Tutorials


E-commerce Website - Online Book Store - Create User Admin Module - Part 3 | JavaInUse
     
 

   
   

E-commerce Website - Online Book Store - Create User Admin Module - Part 3

In this tutorial series we will be developing an ecommerce website for buying books. In a previous tutorial we created the users module to to add new user. In this tutorial we will be creating the view user module using which we can view existing user details. Also we can delete an existing user.

Ecommerce Website - Online Book Store using Angular 8 + Spring Boot

Ecommerce Website - Online Book Store using Angular 8 + Spring Boot Introduction Ecommerce Website - Online Book Store - Create Menu Module Ecommerce Website - Online Book Store - Create User Admin Module - Part 1 Ecommerce Website - Online Book Store - Create User Admin Module - Part 2 Ecommerce Website - Online Book Store - Create User Admin Module - Part 3 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 1 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 2 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 3 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 4 Ecommerce Website - Online Book Store - Create Book Shopping Module

Video

This tutorial is explained in the below Youtube Video.

Spring Boot Application

We will be modifying the Spring Boot Application we had created in the previous tutorial. In the controller class add a method for deleting the User.
package com.javainuse.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.db.UserRepository;
import com.javainuse.model.User;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(path = "users")
public class UserController {

	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("/get")
	public List<User> getUsers() {
		return userRepository.findAll();
	}
	
	@PostMapping("/add")
	public void createUser(@RequestBody User user) {
		userRepository.save(user);
	}
	
	@DeleteMapping(path = { "/{id}" })
	public User deleteUser(@PathVariable("id") long id) {
		User user = userRepository.getOne(id);
		userRepository.deleteById(id);
		return user;
	}
}

Angular Code

The page Structure for the User-Admin Page is as follows-

The Users Component will be having two child components - Add User Component and View User Component.

In this tutorial we will be implementing the view/delete user component. Create a new component named view user.
ng generate component admin/users/viewuser


 We have already added the show details button in the user component. On this click the view user component  should be called along with the user details displayed. So whenever we will load the users component we will also be checking the url component  
  •  if the url has action=add then the adduser page will be displayed.  
  • If the url has the  action=view then the view user page will be displayed.  
  • if no action parameter is present  then neither the add user page or the view user page will be displayed.  
  In Users component, we will be  
  •   In the constructor add the activatedRoute and router.  
    •  ActivatedRoute - Gives us access to the current route instance.
    •  Router - using this we can navigate to another page.
     
  • In the ngOnInit function  we will be  using the ActivatedRoute to check id the url contains any id. If it contains the id it means we have to  show the view page for the selected user.  
  •  Implement the viewUser function. In this function using the Router we will be  again navigating to the same page - /admin/users,  but with additional parameters of action=view and the id of the selected user.  
  •  
import { Component, OnInit } from '@angular/core';
import { User } from '../../model/User';
import { HttpClientService } from '../../service/http-client.service';
import { ActivatedRoute, Router } from '@angular/router';


@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  users: Array<User>;
  selectedUser: User;
  action: string;

  constructor(private httpClientService: HttpClientService,
    private router: Router,
    private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.refreshData();
  }

  refreshData() {
    this.httpClientService.getUsers().subscribe(
      response => this.handleSuccessfulResponse(response),
    );

    this.activatedRoute.queryParams.subscribe(
      (params) => {
        this.action = params['action'];
        const selectedUserId = params['id'];
        if (selectedUserId) {
          this.selectedUser = this.users.find(user => user.id === +selectedUserId);
        }
      }
    );
  }

  handleSuccessfulResponse(response) {
    this.users = response;
  }

  viewUser(id: number) {
    this.router.navigate(['admin','users'], {queryParams : {id, action: 'view'}});
  }

  addUser() {
    this.selectedUser = new User();
    this.router.navigate(['admin', 'users'], { queryParams: { action: 'add' } });
  }
}

   
For displaying the viewuser page in the users page we will be making use of the selector tag of the view user component. We will be showing the view users page only when we have the action parameter as view.  Also we will be specifying the user as selectedUser which will be passed as input to the view user component.
<h1>Users Admin</h1>
<a class="btn btn-primary mb-3" (click)="addUser()">add</a>
<div class="container row">
  <div class="col-md-6">
    <table class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let user of users">
          <td>{{user.id}}</td>
          <td>{{user.name}}</td>
          <td><button type="button" class="btn btn-primary" (click)="viewUser(user.id)">Show Details</button></td>
        </tr>
      </tbody>
    </table>
  </div>
  <div class="col-md-6">
    <app-adduser *ngIf="action === 'add'" [user]="selectedUser" (userAddedEvent)="refreshData()"></app-adduser>
    <app-viewuser *ngIf="action === 'view'" [user]="selectedUser"></app-viewuser>
  </div>
</div>



Also we want to pass the new user that we have created to the child component i.e view/delete user component.  We achieve this using the input tag.    

Finally in the view-users component we create the User named user and decorate it with the Input annotation. This specifies that the user instance will be provided by the parent component to the add user child component whenever it gets called.
import { Component, OnInit, Input } from '@angular/core';
import { User } from '../../../model/User';

@Component({
  selector: 'app-viewuser',
  templateUrl: './viewuser.component.html',
  styleUrls: ['./viewuser.component.css']
})
export class ViewuserComponent implements OnInit {

  @Input()
  user: User

  constructor() { }

  ngOnInit() {
  }

}
Let us now start the application and goto the users page. Click on the Show Details button. We can see that the url has changed with the parameter action=view and the selectedId. Also the view user page can now be seen.

Next we will be modifying the View User Component to take user details and show the user details. Also we will be showing the delete button using which the user will get deleted.
<div class="userDetails">
  <h2>User details</h2>

  <table>
    <tr>
      <td>User Id</td>
      <td>{{user.id}}</td>
    </tr>
    <tr>
      <td>User Name</td>
      <td>{{user.name}}</td>
    </tr>
    <tr>
      <td>User Type</td>
      <td>{{user.type}}</td>
    </tr>

  </table>
  <br>
  <a class="btn btn-small btn-danger" (click)="deleteUser()"> delete</a>
</div>
Next in the HttpClientService we will be adding the deleteUser method. This method will be making a DELETE call to Spring backend to delete the user.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../model/User';


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

  constructor(private httpClient: HttpClient) {
  }

  getUsers() {
    return this.httpClient.get<User[]>('http://localhost:8080/users/get');
  }

  addUser(newUser: User) {
    return this.httpClient.post<User>('http://localhost:8080/users/add', newUser);
  }

  deleteUser(id) {
    return this.httpClient.delete<User>('http://localhost:8080/users/' + id);
  }
 
}
Next we will be modifying the view user component typescript file -
  • In the constructor add the HttpClientService and the Router
  • Define the deleteUser function to delete selected user
import { Component, OnInit, Input } from '@angular/core';
import { User } from '../../../model/User';
import { HttpClientService } from '../../../service/http-client.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-viewuser',
  templateUrl: './viewuser.component.html',
  styleUrls: ['./viewuser.component.css']
})
export class ViewuserComponent implements OnInit {

  @Input()
  user: User

  constructor(private httpClientService: HttpClientService,
    private router: Router) { }

  ngOnInit() {
  }

  deleteUser() {
    this.httpClientService.deleteUser(this.user.id).subscribe(
      (user) => {
        this.router.navigate(['admin', 'users']);
      }
    );
  }

}
If we now run the application Navigate to the view user page and select the user -


If for any user, we click on delete user button the user will get deleted

We can see that the list users is still showing the deleted user.
If we refresh the users page then we can see user is deleted.

If we check the database we can see that new user has been added.

So we need to tell the parent users component that child view user component has deleted an existing User so fetch the users list again. We do this using the Output annotation.

In the view users component file add the Eventemitter. Also if the user is successfully deleted then we send a signal to the parent users component.
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { User } from '../../../model/User';
import { HttpClientService } from '../../../service/http-client.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-viewuser',
  templateUrl: './viewuser.component.html',
  styleUrls: ['./viewuser.component.css']
})
export class ViewuserComponent implements OnInit {

  @Input()
  user: User

  @Output()
  userDeletedEvent = new EventEmitter();

  constructor(private httpClientService: HttpClientService,
    private router: Router) { }

  ngOnInit() {
  }

  deleteUser() {
    this.httpClientService.deleteUser(this.user.id).subscribe(
      (user) => {
        this.userDeletedEvent.emit();
        this.router.navigate(['admin', 'users']);
      }
    );
  }

}
In the users component we specify the function to be called on userDeletedEvent. We have already defined the refreshData function which we will be calling.
<h1>Users Admin</h1>
<a class="btn btn-primary mb-3" (click)="addUser()">add</a>
<div class="container row">
  <div class="col-md-6">
    <table class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let user of users">
          <td>{{user.id}}</td>
          <td>{{user.name}}</td>
          <td><button type="button" class="btn btn-primary" (click)="viewUser(user.id)">Show Details</button></td>
        </tr>
      </tbody>
    </table>
  </div>
  <div class="col-md-6">
    <app-adduser *ngIf="action === 'add'" [user]="selectedUser" (userAddedEvent)="refreshData()"></app-adduser>
    <app-viewuser *ngIf="action === 'view'" [user]="selectedUser" (userDeletedEvent)="refreshData()"></app-viewuser>
  </div>
</div>
Now if we go to localhost:4200/admin/users and select an existing user-

On clicking Delete button the existing user gets immediately deleted in the users list.

Download Source Code

Download it -
Spring Boot + Ecommerce
Angular8 Online Book Store

 

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions