angular - http在Angular中调用api失败

标签 angular http

有如下代码:

#home.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  constructor(private http: HttpClientModule) {}
  id: number;
  private headers = new Headers({ 'Content-Type': 'application/json' });
  person = [];
  fetchData = function() {
    this.http
      .get('http://localhost:5555/person')
      .subscribe((res: Response) => {
        this.person = res;
      });
  };

  deleteProduct = function(id) {
    if (confirm('Are you sure?')) {
      const url = `${'http://localhost:5555/person'}/${id}`;
      return this.http
        .delete(url, { headers: this.headers })
        .toPromise()
        .then(() => {
          this.fetchData();
        });
    }
  };

  ngOnInit() {
    this.fetchData();
  }
}

当我加载此页面时,我在浏览器控制台中收到以下错误:

HomeComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: this.http.get is not a function
    at HomeComponent.fetchData (home.component.ts:16)
    at HomeComponent.push../src/app/home/home.component.ts.HomeComponent.ngOnInit (home.component.ts:35)
    at checkAndUpdateDirectiveInline (core.js:20644)
    at checkAndUpdateNodeInline (core.js:21908)
    at checkAndUpdateNode (core.js:21870)
    at debugCheckAndUpdateNode (core.js:22504)
    at debugCheckDirectivesFn (core.js:22464)
    at Object.eval [as updateDirectives] (HomeComponent_Host.ngfactory.js? [sm]:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:22456)
    at checkAndUpdateView (core.js:21852)

为什么 .get 在这里失败了? vscode 没有对我尖叫。这是 Angular 的第 7 版。

最佳答案

你的构造函数参数应该来自 HttpClient 而不是 HttpClientModule,

将导入更改为,

import { HttpClient } from '@angular/common/http';

和构造函数,

constructor(private http: HttpClient) {}

关于angular - http在Angular中调用api失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53524173/

相关文章:

c++ - 你如何从 HTTP 打开 C++ 中的文件,其中 URL 不是文件位置

javascript - 使用 Jquery 从 url 获取响应

Angular 使用 Karma 和 Jasmine TypeError : this. Service.<foo> 不是 Lifecycle Hook 中的函数

javascript - Angular2、Typescript - 类变量和 "this"的用法

angular - Angular 模型驱动的 react 形式中的两种方式(双)绑定(bind)

node.js - NG Build 在 Azure Pipelines 中失败,出现 NPM 错误 134

php - 来自 WikiMedia API 的 cURL HTTP 请求不起作用

c# - 每 60 秒向 RoR 应用程序发送一次 http put 请求的问题

swift - Swift 2 中的 HTTP 错误

css - 如何在不同的设备上改变整体风格?