How to fetch specific JSON data in Angular

Patty

I am looking to fetch the details 'Contacts' from the below JSON.

{
"id": "65664546",
"name": "Employee 1",
"contacts": [
    {
        "id": "56546564",
        "firstName": "James",
        "lastName": "Carter",
        "email": "[email protected]"
    },
    {
        "id": "565465644",
        "firstName": "Simon",
        "lastName": "Deol",
        "email": "[email protected]"
    }
]

}

Below is the interface I have defined:

export interface employee {
  id: string;
  name: string;
  contacts: contact[];
}

export interface contact {
  firstName: string;
  lastName: string;
  email: string;
}

Please can you advise, what would the Httpget method and subscribe method for it look like.

suraj rawat

You have to use pluck rxjs operator to get specific key data from object and below is the code to get and subscribe data from API.

Here is the Working Example

appcomponent.ts

import { Component, VERSION } from "@angular/core";
import { pluck } from "rxjs/operators";
import { GetServiceService } from "./get-service.service";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;
  constructor(private getAPI: GetServiceService) {}
  ngOnInit() {
    this.getAPI
      .getData()
      .pipe(pluck("contacts"))
      .subscribe(r => {
        console.log(r);
      });
  }
}

getService.ts

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { employee } from "./interface";


  export interface employee {
  id: string;
  name: string;
  contacts: contact[];
}

export interface contact {
  firstName: string;
  lastName: string;
  email: string;
}
@Injectable()
export class GetServiceService {
  constructor(private httpClient: HttpClient) {}
  getData(): Observable<employee> {
    // this.httpClient.get('url for api will be used')
    return of({
      id: "65664546",
      name: "Employee 1",
      contacts: [
        {
          id: "56546564",
          firstName: "James",
          lastName: "Carter",
          email: "[email protected]"
        },
        {
          id: "565465644",
          firstName: "Simon",
          lastName: "Deol",
          email: "[email protected]"
        }
      ]
    });
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related