【问题标题】:how to fetch data from json in angular 4如何从角度4中的json获取数据
【发布时间】:2018-11-21 03:33:17
【问题描述】:

大家好,请帮助我,我有 Json 字符串,这是我从 Node api 获取的。我只想要该字符串中的单个值。

我有 service.ts,我从中调用 api 并订阅我的组件文件上的数据。

Json 字符串为 [{"_id":5,"name":"ram,shyam,kamal,kishore"}]

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

service.ts 代码如下

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

  }

component.ts 代码如下

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

 }

它不起作用,并且此代码中的 response.json() 行也出现错误。 请帮帮我

【问题讨论】:

  • 您使用的 Angular 的确切版本是什么?
  • 你试过response[0].name吗?
  • @SiddAjmer 我正在使用 Angular 4
  • 4.什么? 4.0 还是 4.3?
  • localhost:3000/api/Employee 是否只返回员工姓名?

标签: json angular api


【解决方案1】:

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

如果您使用的是HttpClient,那么:

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

在你的组件中:

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

如果您使用Http(在 Angular 4.3 BTW 中引入 HttpClient 后已弃用),那么:

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
    });
}

【讨论】:

  • 感谢您的宝贵意见。错误没有出现,但我仍然没有得到 name 的值。它显示的是空白值
  • @user1220461,尝试将response 内的response 记录到控制台并告诉我您在屏幕上看到了什么?根据 OP,它是一个只有一个对象的数组。这个对象中有一个名为name 的键。因此,我们通过编写this.name = response[0].name 将其分配给类属性name
  • .它显示错误 response.json is not a function
  • 你的代码中http的类型是什么?是Http 还是HttpClient?
  • 现在我正在使用 HttpClient 。错误消失了,控制台中的结果如下 0: {_id: 5, name:"ram,shyam,kamal,kishore"}
猜你喜欢
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 2021-11-11
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
相关资源
最近更新 更多