2017-07-26 109 views
1

我想实现在角2错误加载@角/普通/ HTTP - 角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"); 

} 

} 

一切工作正常,但一旦我在组件类下的构造函数中创建服务实例,我在CONSOL中得到一个错误即

错误加载 http://localhost:3002/node_modules/@angular/common/bundles/common.umd.js/http 为 “@角/普通/ HTTP” 从 http://localhost:3002/app/app.service.js

如果我删除构造的一部分,我得到的输出。

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

我做错了什么?

+1

你检查https://stackoverflow.com/questions/45207615/cannot-find-the-angular-common-http-module/45207765?你的模块是什么样的? – echonax

+0

我确实检查过。它没有解决我的问题。我仍然收到错误 –

+0

您是否已将HttpClientModule导入您的应用模块? –

回答

-1

导入的HttpModule在app.module像下面

import { HttpModule} from '@angular/http' 

服务导入的Http如下

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

解决了这个问题。

+0

这是没有意义的,因为你是使用HttpClient的为您服务,而不是http依赖。如果你现在正在使用HTTP作为该编辑您的问题可以当我使用的HttpClient和HttpClientModule会误导别人 –

+0

@ Jota.Toledo,我是不是能够导入这些类,因为@ angular/common/http在我安装的npm registery中不可用,这就是为什么我必须将它更改为Http和HttpModule,我希望这可以清除它。 –