【问题标题】:How to have Angular's HttpClient return an object instead of a string?如何让 Angular 的 HttpClient 返回一个对象而不是一个字符串?
【发布时间】:2019-09-24 16:16:40
【问题描述】:

如何让 HttpClient 将数据作为 JSON 对象返回?

Angular 文档说 HttpClient 应该将返回的 JSON 数据解析为一个对象。在我的项目中,它只将数据作为字符串返回。

如果我使用JSON.parse,我可以将数据转换为对象并以这种方式获取数据并且它可以工作。但从我在文章中看到的情况来看,这不是好的做法。此外,大多数文章/教程仅使用接口。

我创建了一个界面并尝试使用它,但它不起作用。看了很多帖子和文章,都说HttpClient应该默认返回一个对象。

这是我的服务中的代码。 第一个函数获取用户坐标,第二个函数使用坐标向api请求数据。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
import { Aqi } from './aqi';

@Injectable({
  providedIn: 'root'
})
export class AqiService {
  aqiUrlCoords = `${environment.apiUri}airvisual/geo/`;

  constructor(private http: HttpClient) {}

  getLocation(): Observable<any> {
    return Observable.create(observer => {
      if(window.navigator && window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(
          (position) => {
            observer.next(position);
            observer.complete();
          },
          (error) => observer.error(error)
        );
      } else {
        observer.error('Unsupported Browser');
      }
    });
  }

  getGeoLocationAqi(lat, long): Observable<any> {
    return this.http.get<any>(this.aqiUrlCoords, { params: {
      lat: lat,
      long: long
    }});
  }

}

要让getGeoLocationAqi() 函数工作,我必须使用它...

getGeoLocationAqi(lat, long): Observable<any> {
    return this.http.get<any>(this.aqiUrlCoords, { params: {
      lat: lat,
      long: long
    }}).pipe(
      map(res => {
        return JSON.parse(res);
      })
    );
  }

这是使用服务和数据的组件。 typeof 总是打印字符串。

import { Component, OnInit } from '@angular/core';
import { AqiService } from '../services/aqi/aqi.service';
import { Aqi } from './aqi';

export class GeoComponent implements OnInit {
  aqi: any;
  errorMessage: string;

  constructor(private aqiService: AqiService) {}

  ngOnInit() {
    this.getCurrentCoordinatesAqi();
  }

  getCurrentCoordinatesAqi() {
    this.aqiService.getLocation().subscribe(pos => {
      let lat = pos.coords.latitude.toString();
      let long = pos.coords.longitude.toString();
      this.aqiService.getGeoLocationAqi(lat, long).subscribe((res) => {
        this.aqi = res;
        console.log(res);
        console.log(typeof res);
      });
    }, (err) => {
      this.errorMessage = err;
    });
  }
}

这是我制作的界面。

export interface Aqi {
  status: string,
    data: {
        city: string,
        state: string,
        country: string,
        location: {
            type: string,
            coordinates: [
              number,
              number
            ]
        },
        current: {
            weather: {
                ts: string,
                hu: number,
                ic: string,
                pr: number,
                tp: number,
                wd: number,
                ws: number
            },
            pollution: {
                ts: string,
                aqius: number,
                mainus: string,
                aqicn: number,
                maincn: string
            }
        }
    }
}

这是使用邮递员从 api 返回的内容。

{
    "status": "success",
    "data": {
        "city": "Hanoi",
        "state": "Hanoi",
        "country": "Vietnam",
        "location": {
            "type": "Point",
            "coordinates": [
                105.81881,
                21.021938
            ]
        },
        "current": {
            "weather": {
                "ts": "2019-04-30T16:00:00.000Z",
                "hu": 100,
                "ic": "04n",
                "pr": 1010,
                "tp": 25,
                "wd": 70,
                "ws": 2.6
            },
            "pollution": {
                "ts": "2019-04-30T15:00:00.000Z",
                "aqius": 151,
                "mainus": "p2",
                "aqicn": 76,
                "maincn": "p2"
            }
        }
    }
}

我希望typeof 打印object,但它总是打印string,除非我使用JSON.parse()。当我使用接口时,我仍然得到字符串。任何帮助表示赞赏!

【问题讨论】:

  • 你真的需要发布那么多代码吗?

标签: json angular typescript


【解决方案1】:

您不需要解析响应,只要您的端点返回 JSON 对象并且内容类型为 application/json,http 客户端默认返回对象。您的端点可能正在返回一些文本内容类型。

【讨论】:

  • 成功了!太感谢了!我的 api 返回一个字符串。我在后端使用JSON.parse 让它发送一个对象。现在我可以在前端使用我的界面了。
  • 你应该为你的 api 使用一个 rest 框架,比如 Nest.js 或 Express.js,而不是自己滚动。
猜你喜欢
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 2021-12-21
  • 2021-07-30
相关资源
最近更新 更多