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

Hòa Nguyễn Thanh
3 min readJun 9, 2020

--

In the content in the previous section, we create all method (GET,PUT,POST,DELELTE) in ASP.NET MVC 5, now need install Angular to project ASP.NET MVC 5
You can see the previous section :
Build Angular + ASP.NET MVC 5
Build Web API using Angular with ASP.NET MVC 5 (Part 1)

Open ClientApp folder in Project ASP.NET MVC 5, we have install it in The Article Build Angular + ASP.NET MVC 5
Create comment.model.ts in ClientApp/src/app directory, config propeties comment

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

Continue, we need create service file , config method GET,PUT,POST,DELETE

  • 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);
}
}
  • REST_API_SERVER : URL Project API ASP.NET MVC 5
  • Config httpOptions: use install request method Post
  • handleError : retrieve error API
  • ClientApp/src/app/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);
});
}
}

The following code above , we need to set up features such as (lists comment,add comment,edit,delete)
Open app.component.html modify the following code below

<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>
  • GetAllComment(): get all data comment
  • EditComment(item.id): call method edit comment
  • DeleteComment(item.id): delete comment
  • AddComment(): add comment
  • checkUpdate: check update comment

Open app.module.ts file, you update the following code below

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 { }

The Article : Build Web API using Angular with ASP.NET MVC5 (Part 2)

--

--