简体   繁体   中英

How can I get the data type from an HTTP response from a Nodejs server in Angular

I'm creating an Angular application connected to a Nodejs backend server. The Nodejs server response can be an array or Json object. I have to catch the correct data type according to the server response.

This is my Angular service code. Note that my HttpClient functions return Json objects. Is there any function that returns any type of data?

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

Thanks a lot !

Check the returned type and transform the response in a map operator, you can then handle it accordingly in your subscribe

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

It's strange behavior for an API to return either an array or object (usually it's always one or the other). I suspect there may be something missing in your understanding/processing of the response, but I could be wrong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM