0

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

12
  • What's the exact version of Angular that you're using? Commented Nov 20, 2018 at 19:09
  • Did you try response[0].name? Commented Nov 20, 2018 at 19:09
  • @SiddAjmer I am using angular 4 Commented Nov 20, 2018 at 19:10
  • 4. what? 4.0 or 4.3? Commented Nov 20, 2018 at 19:10
  • Does localhost:3000/api/Employee only return the employee's name? Commented Nov 20, 2018 at 19:10

1 Answer 1

1

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
    });
}
Sign up to request clarification or add additional context in comments.

10 Comments

thanks for your valuable comment .Error is not coming but still I am not getting the value of name.it is showing blank value
@user1220461, try logging the response inside the subscribe to the console and tell me what you're seeing on the screen? According to the OP, it was an array with just one object in it. This one object had a key named name in it. Hence we assigned it to the class property name by writing this.name = response[0].name
.it is showing error response.json is not a function
What is the type of http in your code? Is it Http or HttpClient?
now I am using HttpClient . error is gone and the result in console is coming like this 0: {_id: 5, name:"ram,shyam,kamal,kishore"}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.