Build Web API using Angular with ASP.NET MVC 5 (Part 2)

Trong nội dung ở phần trước ta đã thiết lập các phương thức GET,POST,PUT,DELETE và đã test ok trên postman, nay ta sẽ cấu hình Angular để gọi các phương thức đó
Đầu tiên hãy mở project củ, và mở thư mục ClientApp, là thư mục Angular của ta
Tạo file comment.model.ts trong thư mục ClientApp/src/app, dùng cấu hình các thuộc tính của comment

export class Comment {
  id: number;
  content: string;
  parent: number;
}

Tiếp theo ta cần tạo file service chứa các phương thức như GET,POST,PUT,DELETE gọi tới APS MVC 5, các bạn có thể xem các phương thức xử lý service trên trang chủ Angular
ClientApp/src/app/comment.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Comment } from './comment.model';
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': 'QYnhwj1SNxOSgd6wMJi5pxyQJXMgUALjc2Ihv9Si' })
};
@Injectable({
  providedIn: 'root',
})
export class CommentService {
  private REST_API_SERVER = 'https://localhost:44332/api';
  constructor(private http: HttpClient) { }

  getAllComment() {
    return this.http.get(this.REST_API_SERVER + '/comment').pipe(catchError(this.handleError));
  }

  /*
  * ADD COMMENT
  * */
  postAddComment(comment: Comment): Observable<any> {
    return this.http.post(this.REST_API_SERVER + '/comment', comment, httpOptions).pipe(catchError(this.handleError));
  }

  /**
   * EDIT COMMENT
   * */
  getComment(id: number) {
    return this.http.get(this.REST_API_SERVER + '/comment/' + id).pipe(catchError(this.handleError));
  }

  /**
   * PUT COMMENT (UPDATE COMMENT)
   * */
  putComment(id: number, comment: Comment): Observable<any> {
    return this.http.put(this.REST_API_SERVER + '/comment/' + id, comment, httpOptions).pipe(catchError(this.handleError));
  }

  /**
   * DELELE COMMENT
   */
  deleteComment(id: number) {
    return this.http.delete(this.REST_API_SERVER + '/comment/' + id).pipe(catchError(this.handleError));
  }

  handleError(error: HttpErrorResponse) {
    let errorMessage = 'Unknown error!';
    if (error.error instanceof ErrorEvent) {
      // Client-side errors
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // Server-side errors
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    window.alert(errorMessage);
    return throwError(errorMessage);
  }

}

Trong đoạn code file comment.service.ts
+ REST_API_SERVER: thông tin URL Project
+ Config httpOptions: dùng xử lý request method Post
+ handleError: function xử lý lỗi nếu không gọi được API
Còn lại các bạn có thể lên search nghiên cứu thêm như(pipe,HttpClient,Observable,..) để hiểu rõ hơn
Sau khi ta cấu hình file comment.service.ts xong, để sử dụng được ta cần import file vào app.comment.ts
ClientApp/src/app/app.comment.ts

import { CommentService } from './comment.service';
constructor(private commentService: CommentService) { }

File full code app.comment.ts

import { Component, OnInit } from '@angular/core';
import { CommentService } from './comment.service';
import {Comment} from './comment.model'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular + ASP MVC 5';
  comments: any;
  commentAdd: string = "";
  commentUpdate: any;
  checkUpdate = false;
  constructor(private commentService: CommentService) { }
  ngOnInit() {
    this.GetAllComment();
  }

/*GET COMMENT*/
  GetAllComment() {
    this.commentService.getAllComment().subscribe(item => {
      this.comments = item;
    });

  }

  /*
   * ADD COMMENT
   */
  AddComment() {
    let _cmt = {
      "id": 10,//you can set id
      "content": this.commentAdd,
      "parent":0,//default 0
    }
    this.commentService.postAddComment(_cmt).subscribe(item => {
      //IF OK
      this.comments = item;
      console.log(item);
    });

    
  }

  /*
   * UPDATE COMMENT
   */
  EditComment(id) {
    this.checkUpdate = true;
    this.commentService.getComment(id).subscribe(item => {
      this.commentUpdate = item;
    });
  }
  UpdateComment() {
   
    let id = this.commentUpdate.id;
    this.commentService.putComment(id, this.commentUpdate).subscribe(item => {
      this.comments = item;
      console.log(item);
    });
    
  }

  /*
   * DELETE COMMENT
   */
  DeleteComment(id: number) {
    this.commentService.deleteComment(id).subscribe(item => {
      this.comments = item;
      console.log(item);
    });
  }
}

Với đoạn code bên trên ta cần thiết lập các tính năng như:(lists comment,add comment,edit,delete)
Bạn nào chưa tìm hiểu Angular thì phải tìm hiểu trước nhé, để hình dung ra cách thức hoạt động của đoạn mã trên

Sau khi ta cấu hình các tính năng trong file app.component.ts xong, ta cần chỉnh giao diện hiển thị tính năng như sau:
Mở file app.component.html lên và cấu hình như sau:

<div>

  <h2>{{title}}</h2>
  <table>
    <tr *ngFor="let item of comments">
      <td>{{item.content}}</td>
      <td><button (click)="EditComment(item.id)" style="color:black">Edit</button></td>
      <td><button (click)="DeleteComment(item.id)" style="color:red">Delete</button></td>
    </tr>
  </table>

  <h2>Add Comment</h2>
  <textarea cols="5" rows="5" [(ngModel)]="commentAdd" style="margin: 0px; width: 255px; height: 62px;"></textarea>
  <br />
  <button (click)="AddComment()">Add Comment</button>

  <div class="form" *ngIf="checkUpdate">
    <h2>Update Comment</h2>
    <label>id</label><br />
    <input type="number" name="idComment" [(ngModel)]="commentUpdate.id" /><br />
    <label>content</label><br />
    <textarea cols="5" rows="5" name="ContentComment" [(ngModel)]="commentUpdate.content"> </textarea><br />
    <label>parent</label><br />
    <input type="number" name="ParentComment" [(ngModel)]="commentUpdate.parent" /><br />
    <button (click)="UpdateComment()">Update Comment</button>
  </div>
 

</div>

+ Đầu tiên hiển thị danh sách dữ liệu comment
+ EditComment(item.id): dùng gọi phương thức edit trong file app.component.ts
+ DeleteComment(item.id): xóa dữ liệu tại id nào đó
+ AddComment(): gọi phương thức thêm dữ liệu
+ checkUpdate: nếu true thì người dùng đang muốn chỉnh sửa , sẽ hiện ra form edit, ngược lại false

Ok sao đó hãy mở file app.module.ts chỉnh sửa lại như sau:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Ngon lành, giờ ta chỉ cần build nó ra và chạy thử nghiệm thôi, nếu các bạn có xem video Build Angular + ASP MVC 5, thì tại bước này ta cũng build y chang vậy
ng build --prod
Sau khi build xong, thì hay run project ASP lên là xong nhé! mọi người có thể làm và phát triển theo ý mình

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)