【问题标题】:why angular application not able to get HTTP response data?为什么 Angular 应用程序无法获取 HTTP 响应数据?
【发布时间】:2020-03-17 20:15:49
【问题描述】:

开始学习 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 错误”,网址:“http://www.mocky.io/v2/5e712acd30000029007a34b8”…}

stackblitz 演示应用的链接:

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

【问题讨论】:

  • 问题是URL,这个模拟API使用https,试试url = 'https://www.mocky.io/v2/5e712acd30000029007a34b8';

标签: angular typescript dependency-injection angular-httpclient angular2-observables


【解决方案1】:

您的问题是您的界面与您的回复不符。

如果您的 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;
}

您的模拟 API 网址也应该是 https。

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

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 2017-12-20
    • 2020-05-15
    • 2018-09-14
    • 2016-10-28
    • 2017-05-17
    • 2017-02-21
    • 2018-02-14
    相关资源
    最近更新 更多