0

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

1
  • The problem is the URL, this mocky API uses https, try url = 'https://www.mocky.io/v2/5e712acd30000029007a34b8'; Commented Mar 17, 2020 at 20:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.