2017-07-26 106 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,我希望這可以清除它。 –