Search code examples
angulartypescriptdependency-injectionangular-httpclientangular2-observables

why angular application not able to get HTTP response data?


Started to learn angular services and DI but stuck trying to get json data from url in a service. This is the service.ts code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Employees } from '../models/emp';

@Injectable()
export class EmployeeService {

  url = 'http://www.mocky.io/v2/5e712acd30000029007a34b8';

  constructor(
    private http: HttpClient
  ) { }

  getEmployees(): Observable<Employees> {
    // make http request to the given url and fetch the contacts
    return this.http.get<Employees>(this.url);
  }

}

Error in console:

HttpErrorResponse {headers: {…}, status: 0, statusText: "Unknown Error", url: "http://www.mocky.io/v2/5e712acd30000029007a34b8"…}

Link to stackblitz demo app:

https://stackblitz.com/edit/angular-osuap2


Solution

  • Your issue is that your interface doesn't match your response.

    If your API response is

    {
       "empList": [
            {"id": 1, "name": "emp1", "city": "city1"},
            {"id": 2, "name": "emp2", "city": "city2"},
            {"id": 3, "name": "emp3", "city": "city3"},
            {"id": 4, "name": "emp4", "city": "city4"}
        ]    
    }
    

    And you are making the following request:

    getEmployees(): Observable<Employees> {
      // make http request to the given url and fetch the contacts
      return this.http.get<Employees>(this.url);
    }
    

    Then your Employees interface needs to match the response:

    export interface Employees {
      empList: Employee[];
    }
    
    export interface Employee {
      id: number;
      name: string;
      city: string;
    }
    

    Your mock API url should also be https.

    DEMO: https://stackblitz.com/edit/angular-mr9dz4