CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

Tạo ứng dụng Angular gọi Restful Webservice (JAX-RS, Jersey)

Đăng lúc: 09:44 PM - 06/12/2023 bởi Charles Chung - 487

Trong bài viết này tôi sẽ hướng dẫn các bạn tạo ứng dụng Angular để gọi Restful Webservice đã tạo tại các bài viết trước.

Chuẩn bị

Tạo dự án Angular

  • Mở cửa sổ dòng lệnh của windows

  • Di chuyển đến thư mục cần tạo dự án và gõ lệnh

> ng new ConsumeRestfulWebserviceAngular --no-standalone

.................(y/N) gõ Enter

.................(y/N) gõ y rồi Enter

  • Di chuyển đến thư mục project

> cd ConsumeRestfulWebserviceAngular

  • Gõ tiếp lệnh tạo models

> ng g class models/Student

> ng g class models/Result

  • Gõ tiếp lệnh tạo services

> ng g service services/Student

  • Gõ tiếp các lệnh tạo components 

> ng g c components/home

> ng g c components/student

> ng g c compoments/student/studentform

> ng g c components/about

> ng g c components/notfound

  • Gõ tiếp lệnh để mở project ở Visual Code 

> code .

  • Mở file index.html sửa đổi như sau

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Gọi RestfulWebService trong Angular</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>

<body>

  <app-root></app-root>

  <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>

  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

</body>

</html>

  • Mở tệp app.component.html sửa code như sau

<div class="container">

  <div class="jumbotron text-center" style="margin-bottom:0">

      <h1>GỌI RESTFUL WEBSERVICE TRONG ANGULAR</h1>

      <p>Đường tuy ngắn không đi không đến, việc tuy nhỏ không làm không xong!</p>

      <a routerLink="home">Trang chủ</a> | <a routerLink="student">Sinh viên</a> | <a routerLink="about">Giới thiệu</a>

    </div>

    <router-outlet></router-outlet>

</div>

  • Mở tệp app.module.ts import thêm 2 module sau

imports: [

    BrowserModule,

    AppRoutingModule,

    HttpClientModule,

    FormsModule,

  ]

  • Mở tệp app-routing.module.ts khai báo các route sau

const routes: Routes = [

  { path:'',component:HomeComponent },

  { path:'home',component:HomeComponent },

  { path:'student',component:StudentComponent },

  { path:'addStudent',component:StudentformComponent},

  { path:'editStudent/:id',component:StudentformComponent},

  { path:'about',component:AboutComponent },

  { path: '**',component: NotfoundComponent }

];

  • Mở tệp models/result.ts bổ sung code sau

export class Result {

    code?:number;

    message?:string;

    constructor(code?:number,message?:string){

        this.code=code;

        this.message=message;

    }

}

  • Mở tệp models/student.ts bổ sung code sau

export class Student {

    studentId?: string;

    fullName?: string;

    gender?: number;

    birthDay?: string;

    email?: string;

    phone?: string;

    address?: string;

    active?: number;

    constructor(studentId?: string,

        fullName?: string,

        gender?: number,

        birthDay?: string,

        email?: string,

        phone?: string,

        address?: string,

        active?: number) {

        this.studentId = studentId;

        this.fullName = fullName;

        this.gender = gender;

        this.birthDay = birthDay;

        this.email = email;

        this.phone = phone;

        this.address = address;

        this.active = active;

    }

}

  • Mở tệp services/student.service.ts bổ sung code sau

import { Injectable } from '@angular/core';

import {HttpClient} from '@angular/common/http';

import { Observable } from 'rxjs';

import { Student } from '../models/student';

import { Result } from '../models/result';

@Injectable({

  providedIn: 'root'

})

export class StudentService {

  uri:string="http://localhost:8080/RestfulWebServiceJerseyOracle/api/students";

  constructor(private client:HttpClient) { }

  getAll=():Observable<Student[]>=>{

    return this.client.get<Student[]>(this.uri);

  }

  search=(name:any):Observable<Student[]>=>{

    return this.client.get<Student[]>(this.uri+"/search/"+name);

  }

  getById=(id:any):Observable<Student>=>{

    return this.client.get<Student>(this.uri+"/"+ id);

  }

  update=(id:any,student:Student):Observable<Result>=>{

    return this.client.put(this.uri+"/"+id,student)

  }

  insert=(student:Student):Observable<Result>=>{

    return this.client.post(this.uri,student)

  }

  delete=(id:any):Observable<Result>=>{

    return this.client.delete(this.uri+"/"+id)

  }

}

  • Mở tệp components/home/home.component.html bổ sung code sau

<h3>Hệ thống bài thực hành môn Xây dựng dịch vụ Web với Java</h3>

<p>Bài 1: Phát triển ứng dụng RESTful Web Service trong Java với thư viện Jersey</p>

<p>Bài 2: Tạo RESTful Web Service trong Java với Jersey và Oracle</p>

<p>Bài 3: Restful Webservice Upload file kèm dữ liệu JSON sử dụng Jersey trong Java và Oracle</p>

<p>Bài 4: Security trong Restful Webservice sử dụng Jersey 2 để sinh ra JWT</p>

<p>Bài 5: Tạo ứng dụng JSP-Servlet gọi Restful Webservice sử dụng thư viện Jersey Client</p>

<p>Bài 6: Enable CORS trong Restful Webservice(JAX-RS, Jersey) và Tạo ứng dụng Client sử dụng Ajax JQuery</p>

<p>Bài 7: Tạo ứng dụng Angular gọi Restful Webservice (JAX-RS, Jersey)</p>

<p>Bài 8: Tạo ứng dụng ReactJS gọi Restful Webservice (JAX-RS, Jersey)</p>

  • Mở tệp components/student/student.component.ts bổ sung code sau

import { Component } from '@angular/core';

import { ActivatedRoute } from '@angular/router';

import { Result } from 'src/app/models/result';

import { Student } from 'src/app/models/student';

import { StudentService } from 'src/app/services/student.service';

declare var $: any;

@Component({

  selector: 'app-student',

  templateUrl: './student.component.html',

  styleUrls: ['./student.component.css']

})

export class StudentComponent {

  title: string = "Danh sách sinh viên";

  students: Array<Student> = [];

  res:any;

  constructor(private studentService: StudentService, private route: ActivatedRoute) { }

  ngOnInit(): void {

    this.studentService.getAll().subscribe(data => {

      this.students = data;

    });

  }

  deleteStudent=(id:any):void=>{

    if(confirm('Bạn có muốn xóa không?')){

      this.studentService.delete(id).subscribe({

        next: (v) => {

         // window.location.reload();

         $('#'+id).remove();

        }, error: (e) => {

          this.res = new Result(e.status, e.error.msg ?? e.statusText);

        }

      })

    }

  }

}

  • Mở tệp components/student/student.component.html bổ sung code sau

<h3>{{title}}</h3>

<a routerLink="/addStudent">Thêm sinh viên</a>

<hr>

<table class="table table-bordered">

    <tr>

        <th>Mã số</th>

        <th>Họ và tên</th>

        <th>Giới tính</th>

        <th>Ngày sinh</th>

        <th>Email</th>

        <th>Điện thoại</th>

        <th>Địa chỉ</th>

        <th>Tình trạng</th>

        <th></th>

    </tr>

    <tr *ngFor="let s of students" id="{{s.studentId}}">

        <td>{{s.studentId}}</td>

        <td>{{s.fullName}}</td>

        <td>{{s.gender==1?'Nam':'Nữ'}}</td>

        <td>{{s.birthDay}}</td>

        <td>{{s.email}}</td>

        <td>{{s.phone}}</td>

        <td>{{s.address}}</td>

        <td>{{s.active==1?'Đang học':'Dừng'}}</td>

        <td>

            <a class="btn btn-success btn-circle btn-sm" routerLink="/editStudent/{{s.studentId}}">Sửa</a> |<a  class="btn btn-danger btn-circle btn-sm" (click)="deleteStudent(s.studentId)">Xóa</a>

        </td>

    </tr>

</table>

  • Mở tệp components/student/studentform/studentform.component.ts bổ sung code sau

import { Component } from '@angular/core';

import { ActivatedRoute, Router } from '@angular/router';

import { Result } from 'src/app/models/result';

import { Student } from 'src/app/models/student';

import { StudentService } from 'src/app/services/student.service';

@Component({

  selector: 'app-studentform',

  templateUrl: './studentform.component.html',

  styleUrls: ['./studentform.component.css']

})

export class StudentformComponent {

  st: any;

  title: string = "Thêm mới sinh viên";

  res: any;

  btn_title: string = "Lưu";

  id: any;

  constructor(private services: StudentService, private route: ActivatedRoute, private router: Router) {

   }

  ngOnInit(): void {

    this.id = this.route.snapshot.paramMap.get('id');//lấy tham số id

    if (this.id != null) {

      this.services.getById(this.id).subscribe({

        next: (v) => {

          this.st = v;

        },

        error: (e) => {

          this.res = new Result(e.status, e.error.msg ?? e.statusText);

        }

      });

    }

    this.st = new Student();

   }

  insertOrUpdateStudent = (): void => {

    if (this.id != null) {

      //xử lý ngày tháng nulll

      this.st.birthDay = (this.st.birthDay == '' || this.st.birthDay == undefined) ? '1970-01-01' : this.st.birthDay;

      //update

      this.services.update(this.id, this.st).subscribe({

        next: (v) => {

          this.res = v;

          this.router.navigate(['/student']);

        }, error: (e) => {

          this.res = new Result(e.status, e.error.msg ?? e.statusText);

        }

      });

    } else {

      //xử lý ngày tháng nulll

      this.st.birthDay = (this.st.birthDay == '' || this.st.birthDay == undefined) ? '1970-01-01' : this.st.birthDay;

      if (this.st.studentId == null || this.st.studentId == '') {

        this.res = new Result(501, "Hãy nhập mã sinh viên!");

        return;

      }

      //insert

      this.services.insert(this.st).subscribe({

        next: (v) => {

          this.router.navigate(['/student']);

        }, error: (e) => {

          console.log(e);

          this.res = new Result(e.status, e.error.msg ?? e.statusText);

        }

      });

    }

  }

}

  • Mở tệp components/student/studentform/studentform.component.html bổ sung code sau

<div class="d-sm-flex align-items-center justify-content-between mb-4">

    <h1 class="h3 mb-0 text-gray-800">{{title}}</h1>

</div>

<div class="text-danger">{{res?.message}}</div>

<form>

    <div class="row">

        <div class="col-md-6">

            <div class="form-group">

                <label for="studentId">Mã sinh viên</label>

                <input required="required" type="text" class="form-control" id="studentId" [(ngModel)]="st.studentId"

                    name="studentId">

            </div>

            <div class="form-group">

                <label for="fullName">Họ và tên</label>

                <input required="required" type="text" class="form-control" id="fullName" [(ngModel)]="st.fullName"

                    name="fullName">

            </div>

            <div class="form-group">

                <label for="birthDay">Ngày sinh</label>

                <input type="date" class="form-control" id="birthDay"

                [ngModel]="st.birthDay|date:'yyyy-MM-dd'"

                (ngModelChange)="st.birthDay=$event" name="birthDay" />

            </div>

            <div class="form-group"><label for="gender">Giới tính</label>

                <select class="form-control" id="gender" name="gender">

                    <option value="1">Nam</option>

                    <option value="0">Nữ</option>

                </select>

            </div>

        </div>

        <div class="col-md-6">

            <div class="form-group">

                <label for="email">Email</label>

                <input type="email" class="form-control" id="email" [(ngModel)]="st.email" name="email">

            </div>

            <div class="form-group">

                <label for="phone">Điện thoại</label>

                <input type="text" class="form-control" id="phone" [(ngModel)]="st.phone" name="phone">

            </div>

            <div class="form-group">

                <label for="address">Địa chỉ</label>

                <input type="text" class="form-control" id="address" [(ngModel)]="st.address" name="address" />

            </div>

            <div class="form-group"><label for="active">Tình trạng</label>

                <select class="form-control" id="active" name="active">

                    <option value="1">Đang học</option>

                    <option value="0">Dừng</option>

                </select>

            </div>

        </div>

    </div><button type="button" (click)="insertOrUpdateStudent()" class="btn btn-primary">{{btn_title}}</button> &nbsp;

    <a href="javascript:history.back()" class="btn btn-info">Quay lại</a>

</form>

Run ứng dụng: tại cửa sổ dòng lệnh gõ lệnh sau để chạy

> ng serve -o

  • Màn hình sinh viên

  • Màn hình thêm sinh viên

Video demo

Link tải source code

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ