【问题标题】:How to parse the Json array from Json object using angular如何使用角度从 Json 对象解析 Json 数组
【发布时间】:2020-12-12 18:10:27
【问题描述】:

在 Angular 应用程序中,我调用了 API 并读取了 Json 对象 inconsole 。但是 Json 对象内部有字符串和数组。现在我必须从对象 incosole 解析数组。

我在控制台中得到的对象是:

{
"Drone": {
    "Droneid": 1001,
    "latlong": [
        {
            "lat": 12.989839,
            "lon": 80.198822
        },
        {
            "lat": 13.051832,
            "lon": 80.194480
        },
        {
            "lat": 13.038453,
            "lon": 80.227442
        },
        {
            "lat": 13.009018,
            "lon": 80.242550
        },
        {
            "lat": 12.976903,
            "lon": 80.237056
        },
        {
            "lat": 12.956829,
            "lon": 80.193107
        },
        {
            "lat": 12.980917,
            "lon": 80.150531
        },
        {
            "lat": 13.007680,
            "lon": 80.149158
        },
        {
            "lat": 13.043805,
            "lon": 80.154651
        }
    ]
}
}

但我必须从对象中解析 latlong 数组。

Dashboard.service.ts

mapping(token){
  let httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json',
      'Authorization': 'Token ' + token
    })
  };
  //this.http.get(this.url).subscribe(
    this.http.get(environment.apiurl +'/api/data/json', httpOptions).subscribe(  
    (dronesdt:any)=>{
      localStorage.setItem("dronesdt",JSON.stringify(dronesdt));
      console.log("Drones",JSON.parse(localStorage.getItem("dronesdt")));
 } 
  )
}

那么如何在控制台中获取 latlong 数组。 谁能帮我解决这个问题。

【问题讨论】:

  • 试试console.log(dronesdt.Drone.latlong);
  • 您是否尝试过声明接口来表示您的结构并使用get => this.http.get<Drone>(...) 的通用版本?
  • 不,我之前没有涉足这个领域,请你帮我表示所需的json对象的结构..我的目标是从对象中接收latlong数组。
  • 关于这个主题有多个教程/答案可以找到,例如stackoverflow.com/questions/54625967/…

标签: angular typescript api angular8


【解决方案1】:

您可以像这样获取latlong 字段:

dashboard.service.ts

mapping(token){
  let httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json',
      'Authorization': 'Token ' + token
    })
  };
  // this.http.get(this.url).subscribe(
    this.http.get(environment.apiurl +'/api/data/json', httpOptions).subscribe(  
    (dronesdt:unknown /*Try to avoid any and statically type values as far as possible*/)=>{
      localStorage.setItem("dronesdt",JSON.stringify(dronesdt));
      console.log("Drones", dronesdt.Drone.latlong);
 } 
  // )
}

无需在控制台中JSON.parse 对象,因为您已经在该函数中获取了最新数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 2019-01-14
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多