user1220461
user1220461

Reputation: 81

how to fetch data from json in angular 4

Hi everyone plz help me I have Json string which is I am getting from Node api .I want only single value from that string.

I have service.ts from which I am calling api and subscribe the data on my component file .

Json string is [{"_id":5,"name":"ram,shyam,kamal,kishore"}]

I want only name value. how to achieve this.

service.ts code is given below

empservicecall() {
    return this.http.get("http://localhost:3000/api/Employee")

  }

component.ts code is given below

GetEmpName(){
   this.Emp.empservicecall()
   .subscribe(
     response =>{
       this.name=response.json})

 }

it is not working and also error is coming in this code at line response.json(). plz help me

Upvotes: 0

Views: 2973

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

The solution to your issue completely depends on which version of Angular you are on and whether you're using Http or HttpClient.

If you're using HttpClient, then:

empservicecall() {
  return this.http.get("http://localhost:3000/api/Employee");
}

And in your Component:

GetEmpName(){
  this.Emp.empservicecall()
    .subscribe(response => {
      console.log(response);
      this.name = response[0].name
    });
}

If you're using Http(which has been deprecated after the introduction of HttpClient in Angular 4.3 BTW), then:

import 'rxjs/add/operator/map';

empservicecall() {
  return this.http.get("http://localhost:3000/api/Employee")
    .map((res: any) => res.json());
}

And in your Component:

GetEmpName(){
  this.Emp.empservicecall()
    .subscribe(response => {
      console.log(response);
      this.name = response[0].name
    });
}

Upvotes: 1

Related Questions