【问题标题】:Error loading @angular/common/http - angular 2加载 @angular/common/http 时出错 - angular 2
【发布时间】:2018-01-01 16:35:34
【问题描述】:

我正在尝试在 Angular 2 中实现一项服务。

服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BrowserModule } from '@angular/platform-browser';


@Injectable()
export class DemoService {


constructor(private http: HttpClient
         ) { }
  GetData(): Observable<String> {
    const baseUrl = 'http://localhost:54037/api/home'; // this  part  will  come from  config  file  in futer
   // const url = '?resourceId=' + primaryId + '&showDate=' + selectedDate;
    // http://localhost:55174/api/Resource?resourceId=3&showDate=2017-06-06
    return this.http
      .get<String>(baseUrl);
  }

}

组件:

import { Component, OnInit } from '@angular/core';
import { DemoService } from './app.service';
import { BrowserModule } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`,

})
export class AppComponent implements OnInit  { 

  constructor(private s: DemoService){} 
  name = 'Angular 2'; 
ngOnInit(){
console.log("Inidialization completed");

}

}

一切正常,但只要我在组件类下的构造函数中创建服务实例,控制台就会出现错误。

加载错误 http://localhost:3002/node_modules/@angular/common/bundles/common.umd.js/http 作为“@angular/common/http”来自 http://localhost:3002/app/app.service.js

如果我删除构造函数部分,我会得到输出。

我需要创建一个构造函数的实例,然后调用服务。

我做错了什么吗?

【问题讨论】:

  • 你检查过stackoverflow.com/questions/45207615/… 吗?你的模块是什么样的?
  • 我检查过了。它没有解决我的问题。我仍然收到错误
  • 您是否将 HttpClientModule 导入到您的应用模块中?
  • @Jota。我是否应该导入 Http、Httpmodule 以及我在服务中使用什么来调用 api.. 有点令人困惑! :(
  • HttpModule 和 HttpClientModule 是 2 个不同的库/包。如果你想在你的应用程序中使用 HttpClient,你需要导入第二个。 angular.io/guide/http

标签: angular angular-services angular-http


【解决方案1】:

在 app.module 中导入 HttpModule,如下所示

import { HttpModule} from '@angular/http'

在服务中导入Http如下

import { Http, Response} from '@angular/http'

解决了问题。

【讨论】:

  • 这毫无意义,因为您在服务中使用 HttpClient 作为依赖项,而不是 http。如果您现在使用 Http,请编辑您的问题,因为这可能会误导其他人
  • @Jota.Toledo 当我使用 HttpClient 和 HttpClientModule 时,我无法导入这些类,因为 @angular/common/http 在我安装的 npm registery 中不可用。这就是为什么我不得不将其更改为 Http 和 HttpModule。我希望这可以清除它。
猜你喜欢
  • 2022-11-10
  • 2016-12-13
  • 1970-01-01
  • 2018-01-21
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
相关资源
最近更新 更多