Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing json response from Http Request in Angular

Tags:

json

angular

I need to parse a json response containing two keys. The response looks like

{
status: 0;
message: 'some error 404'
}

In pure nodejs or React you could just simply do: if (response.status===1)console.log('success').

However, I've been having a tough time doing this in angular. Could someone guide me and tell me how could I parse the JSON Response? I have attached a mock-up of the code.

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
    selector: 'app-create-employee',
    templateUrl: './create-employee.component.html',
    styleUrls: ['./create-employee.component.css']
})

export class CreateEmployeeComponent {
    
    constructor(private http: HttpClient) { };
    
    onFormSubmit() {
        let options = {
            headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
        };
        
        let body = new URLSearchParams();
        body.set('data', 'stackoverflow');
            

        this.http.post('http://localhost:8080/createEmployee', body.toString(), options)
        .subscribe(response => {
            console.log(response.status);
            console.log(response.message);
        });
    }
}
like image 681
Catalyst Avatar asked Mar 14 '26 01:03

Catalyst


1 Answers

According to the documentation, Angular can parse for you objects from string responses if you tell it how to do it. You can use this as an example.

First define an interface inside your component just below your imports:

  export interface Response {
    status: number,
    message: string
  }

This tells angular how to parse the json response from your server. The final bit is to use this interface in your post request like this:

this.http.post<Response>('http://localhost:8080/createEmployee', body.toString(), options)
        .subscribe(response => {
            console.log(response.status);
            console.log(response.message);
        });
like image 50
dopesky Avatar answered Mar 15 '26 15:03

dopesky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!