为什么 angular 应用程序无法获取 HTTP 响应数据?

why angular application not able to get HTTP response data?

开始学习 angular 服务和 DI,但一直试图从服务中的 url 获取 json 数据。 这是 service.ts 代码:

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

}

控制台错误:

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

Link 到 stackblitz 演示应用程序:

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

您的问题是您的界面与您的响应不匹配。

如果您的API回复是

{
   "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"}
    ]    
}

并且您正在提出以下请求:

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

那么您的 Employees 接口需要匹配响应:

export interface Employees {
  empList: Employee[];
}

export interface Employee {
  id: number;
  name: string;
  city: string;
}

你的 mock API url 也应该是 https。

演示:https://stackblitz.com/edit/angular-mr9dz4