如何在angular 4中从json获取数据

如何在angular 4中从json获取数据,json,angular,api,Json,Angular,Api,大家好,请帮助我,我有一个Json字符串,这是我从节点api得到的。我只想从该字符串中得到一个值 我使用service.ts调用api并订阅组件文件中的数据 Json字符串是[{“_id”:5,“name”:“ram,shyam,kamal,kishore”}] 我只需要名称值。如何做到这一点 service.ts代码如下所示 empservicecall() { return this.http.get("http://localhost:3000/api/Employee")

大家好,请帮助我,我有一个Json字符串,这是我从节点api得到的。我只想从该字符串中得到一个值

我使用service.ts调用api并订阅组件文件中的数据

Json字符串是[{“_id”:5,“name”:“ram,shyam,kamal,kishore”}]

我只需要名称值。如何做到这一点

service.ts代码如下所示

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

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

 }
component.ts代码如下所示

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

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

 }
它不起作用,代码中的response.json()行也出现了错误。
plz help me

您的问题的解决方案完全取决于您使用的是哪个版本的Angular,以及您使用的是
Http
还是
HttpClient

如果您使用的是
HttpClient
,则:

empservicecall() {
  return this.http.get("http://localhost:3000/api/Employee");
}
import 'rxjs/add/operator/map';

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

GetEmpName(){
  this.Emp.empservicecall()
    .subscribe(response => {
      console.log(response);
      this.name = response[0].name
    });
}
GetEmpName(){
  this.Emp.empservicecall()
    .subscribe(response => {
      console.log(response);
      this.name = response[0].name
    });
}
如果您使用的是
Http
(在Angular 4.3 BTW中引入
HttpClient
后,它已被弃用),那么:

empservicecall() {
  return this.http.get("http://localhost:3000/api/Employee");
}
import 'rxjs/add/operator/map';

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

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

您使用的Angular的确切版本是什么?您是否尝试了
响应[0]。name
?@SiddAjmer我使用的是Angular 44。什么4.0或4.3?是否只返回员工的姓名?感谢您的宝贵意见。不会出现错误,但我仍然无法获取姓名的值。它显示为空白value@user1220461,尝试将
响应
记录在
订阅
控制台中,并告诉我您在屏幕上看到了什么?根据OP,它是一个数组,其中只有一个对象。这一个对象中有一个名为
name
的键。因此,我们通过编写
this.name=response[0].name
将其分配给类属性
name
。它显示错误响应。json不是函数在代码中的
http
类型是什么?是
Http
还是
HttpClient
?现在我正在使用HttpClient。错误消失了,控制台中的结果如下0:{u id:5,name:“ram,shyam,kamal,kishore”}