如何让Angular的HttpClient返回对象而不是字符串? [英] How to have Angular's HttpClient return an object instead of a string?

查看:171
本文介绍了如何让Angular的HttpClient返回对象而不是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I have HttpClient return the data as a JSON Object?

角度文档说HttpClient应该将返回的JSON数据解析为一个对象.在我的项目中,它仅以字符串形式返回数据.

Angular docs say that HttpClient should parse returned JSON data as an object. In my project, it only returns the data as a string.

如果我使用 JSON.parse ,则可以将数据转换为对象并以这种方式获取数据,然后它就可以工作了.但是从我在文章中看到的情况来看,这不是一个好习惯.另外,大多数文章/教程仅使用界面.

If I use JSON.parse, I can turn the data into an object and get the data that way and it works. But from what I've seen in articles, that is not good practice. Also, most articles/tutorials only use interfaces.

我已经创建了一个界面并尝试使用它,但是它不起作用.我已经阅读了很多文章和文章,但是所有人都说HttpClient应该默认返回一个对象.

I've created an interface and tried using it, but it doesn't work. I've read so many posts and articles, but they all say that HttpClient should return an object by default.

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

Here is the code from my service. The first function gets the user's coordinates, and the second function uses the coordinates to request data from the 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()函数正常工作,我必须使用此...

to get the getGeoLocationAqi() function to work, I have to use this...

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总是打印字符串.

Here is the component that uses the service and data. typeof always prints string.

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返回的内容.

Here is what is returned from the api by using postman.

{
    "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 ,但是除非我使用 JSON.parse() string .>.当我使用接口时,我仍然得到字符串.感谢您的帮助!

I expect typeof to print object, but it always prints string unless I use JSON.parse(). When I use the interface, I still get the string. Any help is appreciated!

推荐答案

您无需解析响应,默认情况下,http客户端返回对象,只要您的端点返回JSON对象且内容类型为application/json.您的端点可能正在返回某种文本内容类型.

You don't need to parse the response, the http client return objects by default as long as your endpoint is returning JSON objects and the content type is application/json. Your endpoint is probably returning some text content type.

这篇关于如何让Angular的HttpClient返回对象而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆