Angular HttpClient - Set Response Type as Text

Angular HttpClient - Set Response Type as Text

In this tutorial we’ll see how to set response type as text when using Angular HttpClient to make a Http request.

Requesting a types response – Angular HttpClient

HttpClient supports HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data and get method to fetch data from a server. With each of these methods you can send options object as an argument that you can use to configure the request. In that object you can set values as key, value pairs and it gives you an option to set HttpHeaders, HttpParams, responseType and other values.

ResponseType options value which you can set are arraybuffer, blob, text, json. Default for response type is {responseType: 'json'}.

Setting response type as text example

In this example we’ll see how to set response type as text while sending HttpClient request to the spring rest API.

In the Spring Boot application we have a Rest Controller class with handler mappings for different CRUD operations. DB used is MySQL and the DB table is User.

To get more details and code for the Spring Boot CRUD application, refer this post- Spring Boot REST API CRUD Example With Spring Data JPA

In the UserController class let’s change the method that handles the delete request to return a String.

// Delete user record
@DeleteMapping(value="/{id}", produces="text/plain")
public String deleteUser(@PathVariable int id){
try {
userService.deleteUserById(id);
return "Successfully deleted";
//return new ResponseEntity<String>(HttpStatus.OK);
}catch(RuntimeException ex){
// log the error message
System.out.println(ex.getMessage());
//return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
return "Error while deleting";
}

As you can see method returns a String "Successfully deleted" if deletion is successful otherwise it returns "Error while deleting".

In the Angular client code when calling delete method you should set {responseType: ‘text’} so that it constructs a DELETE request that interprets the body as a text string and returns a string.

For full Angular code please refer this post- Angular HttpClient to Communicate With Backend Service

In the UserService class deleteUser() method should be changed to set responseType.

deleteUser(id: number){
return this.http.delete(`${this.baseUrl}/${id}`, {responseType:'text'})
.pipe(catchError(this.handleError));
}

Component class (deleteuser.component.ts)

import { Component, OnInit } from "@angular/core";
import { FormControl, FormGroup, Validators } from "@angular/forms";
import { UserService } from "src/app/services/user.service";

@Component({
selector: 'app-deleteuser',
templateUrl: './deleteuser.component.html'
})
export class DeleteUserComponent implements OnInit{
userDeleteForm: FormGroup;
deleteMsg = null;
constructor(private userService: UserService){}
ngOnInit(): void {
this.userDeleteForm = new FormGroup({
userId: new FormControl('', Validators.required),
});
}
onSubmit(){
this.deleteMsg = null;
this.userService.deleteUser(+this.userDeleteForm.value.userId)
.subscribe(responseData=> {
console.log('responseData- ', responseData)
this.deleteMsg = responseData
}, error=>{
this.deleteMsg = error
});
}
}

In the subscribe() method the first function assigns deleteMsg property to the returned responseData from the HttpRequest, which should be the returned string from the backend service.

Template (deleteuser.component.html)

<div class="row">
<div class="col-sm-6, col-md-6">
<h2>Delete User</h2>
<form [formGroup]="userDeleteForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="userId">Enter Id to be deleted</label>
<input type="text" class="form-control" id="userId"
formControlName="userId">
<div class="alert alert-danger" *ngIf="userDeleteForm.get('userId').invalid
&& userDeleteForm.get('userId').touched">
Please enter a valid Id
</div>
</div>
<button type="submit" [disabled]="userDeleteForm.invalid" class="btn btn-success">Submit</button>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-6, col-md-6">
<div class="alert alert-danger" *ngIf="deleteMsg">
<p>{{ deleteMsg }}</p>
</div>
</div>
</div>

With these changes if you make a delete request you should see an appropriate message.

responseType as text Angular HttpClient
Angular HttpClient return responseType as text

That's all for this topic Angular HttpClient - Set Response Type as Text. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Create a Custom Observable in Angular
  2. Forms in Angular
  3. FormArray in Angular With Example
  4. Angular - Call One Service From Another

You may also like-

  1. Pure and Impure Pipes in Angular
  2. Radio Button in Angular Form Example
  3. Angular Access Control CanActivate Route Guard Example
  4. Angular Custom Property Binding Using @Input Decorator
  5. JShell in Java With Examples
  6. Java join() Method - Joining Strings
  7. Local, Nonlocal And Global Variables in Python
  8. Sending Email Using Spring Framework Example
Find Out
Related Post

Ikuti AltairGate.com pada Aplikasi GOOGLE NEWS : FOLLOW (Dapatkan Berita Terupdate tentang Dunia Pendidikan dan Hiburan). Klik tanda  (bintang) pada aplikasi GOOGLE NEWS.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad