Node.js 如何从中的Nodejs服务器的HTTP响应中获取数据类型

Node.js 如何从中的Nodejs服务器的HTTP响应中获取数据类型,node.js,angular,Node.js,Angular,我正在创建一个连接到Nodejs后端服务器的Angular应用程序。Nodejs服务器响应可以是数组或Json对象。我必须根据服务器响应捕获正确的数据类型 这是我的角度服务代码。 请注意,我的HttpClient函数返回Json对象。有没有返回任何类型数据的函数 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rx

我正在创建一个连接到Nodejs后端服务器的Angular应用程序。Nodejs服务器响应可以是数组或Json对象。我必须根据服务器响应捕获正确的数据类型

这是我的角度服务代码。 请注意,我的HttpClient函数返回Json对象。有没有返回任何类型数据的函数

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators'

import { City } from '../models/City';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CityService {

  constructor(private http: HttpClient) { }

  API_URI = 'http://localhost:5000'

  getCities() {
    return this.http.get(`${this.API_URI}/City`);
  }
  
  getCity(id: string) {
    return this.http.get(`${this.API_URI}/City/${id}`);
  }

  deleteCity(id: string) {
    return this.http.delete(`${this.API_URI}/City/${id}`);
  }

  saveCity(city: City) { 
    return this.http.post(`${this.API_URI}/City`, city);
  }

  updateCity(id: string|number|undefined, updatedCity: City): Observable<City> {
    return this.http.put(`${this.API_URI}/City/${id}`, updatedCity);
  }
}

从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClient};
从“rxjs/operators”导入{map}
从“../models/City”导入{City};
从“rxjs”导入{Observable};
@注射的({
providedIn:'根'
})
出口级城市服务{
构造函数(私有http:HttpClient){}
API_URI=http://localhost:5000'
getCities(){
返回this.http.get(`this.API_URI}/City`);
}
getCity(id:string){
返回this.http.get(`this.API_URI}/City/${id}`);
}
deleteCity(id:string){
返回this.http.delete(`this.API_URI}/City/${id}`);
}
拯救城市(城市:城市){
返回this.http.post(`this.API_URI}/City`,City);
}
updateCity(id:string | number |未定义,updatedCity:City):可观察{
返回this.http.put(`this.API_URI}/City/${id}`,updatedCity);
}
}

非常感谢

检查返回的类型并在
映射
操作符中转换响应,然后您可以在
订阅

getCities() {
    return this.http.get(`${this.API_URI}/City`).pipe(
       map( body => {
            return {
                isArray: Array.isArray(body),
                data: body
            }
       })
    )
  }

API返回数组或对象(通常总是一个或另一个)是一种奇怪的行为。我怀疑您对响应的理解/处理中可能缺少一些东西,但我可能是错误的。http响应包含在这些头中,您可以获取服务器发送的
内容类型
头。如果您只是尝试测试返回数据是
数组
还是
对象
,您可以在以下情况下执行
(Array.isArray(someData)){/*我是一个数组*/}其他{/*我是一个对象*/}
,但问题是那些get()、post()、delete()和put()函数根据其定义返回Json对象。我需要一种方法以相应的数据类型获取正文响应。我认为这是我的错误。我没有意识到我可以将这些服务器响应解析为单个数据类型。非常感谢!