【问题标题】:Module has no exported member 'http' [2305]模块没有导出成员“http”[2305]
【发布时间】:2022-05-11 15:20:35
【问题描述】:

您好,我正在尝试从“@angular/common/http”导入 http 调用,并收到错误消息,指出模块没有导出成员“http”

错误:[ts] 模块 '"e:/car/node_modules/@angular/common/http"' 没有导出的成员 'Http'。 [2305]

import {
  RouterModule
} from '@angular/router';
import {
  BrowserModule
} from '@angular/platform-browser';
import {
  NgModule
} from '@angular/core';

import {
  AppRoutingModule
} from './app-routing.module';
import {
  AppComponent
} from './app.component';
import {
  HomeComponent
} from './home/home.component';
import {
  HttpClientModule
} from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    RouterModule.forRoot([{
      path: '',
      component: HomeComponent
    }])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

import {
  Http
} from '@angular/common/http';
import {
  Component,
  OnInit
} from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private http: Http) {}
  products = [];
  fetchData = function() {
    this.http.get('http://localhost:5555/products').subscribe(
      (res: Response) => {
        this.products = res.json();
      }
    );
  };
  ngOnInit() {
    this.fetchData();
  }

}

以下代码用于插入包含详细信息的 json 文件

【问题讨论】:

    标签: angular6


    【解决方案1】:

    HttpClientModule 将注入 HttpClient 服务而不是 Http。

    请在HomeComponent 的构造函数注入中使用HttpClient。

    constructor(private http: HttpClient) {}
    

    供参考创建的示例stackblitz 代码。

    【讨论】:

    • 您好 Ranjit,代码现在可以正常工作,但我无法从 json 服务器获取数据,您能帮我解决这个问题吗?下面是导出类导出类 HomeComponent 实现 OnInit { 构造函数(私有 http: HttpClient) { } 产品 = []; fetchData = function() { this.http.get('localhost:5555/products').subscribe ( (res: Response) => { this.products = res.json(); } ); }; ngOnInit() { this.fetchData(); } }
    • 供参考创建的示例代码stackblitz.com/edit/…
    • 我添加了一个带有一组值的 products.json 文件,并给出了 localhost 地址:5555,但即使在使用 this.http.get('localhost:5555/products').subscribe ( ( res: 响应) => { this.products = res.json(); } );它没有获取数据,也没有在浏览器中显示错误消息 PS:我已经安装了 json 服务器,并且在操作服务器中的值后服务器工作正常,使用“npm install -g json-server”进行安装非常抱歉,如果我有任何愚蠢的错误
    • 使用 this.products = res; 代替 this.products = res.json();。并且检查 chrome 开发工具是 http://localhost:5555/products 返回任何数据。
    • 非常感谢它现在得到的帮助,以防万一有任何问题我会在这里提出另一个问题或评论,如果你有任何教程或链接来学习 CRUD 操作和角度的网格,请发给我
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2017-05-07
    • 2017-08-18
    相关资源
    最近更新 更多