2017-05-08 81 views
3

我想創建自己的http服務,這樣我可以使用它像一個HTTP攔截,但我得到的開頭很長的錯誤:EXCEPTION: Uncaught (in promise): Error: No provider for XHRBackend!角2自定義HTTP服務引發錯誤:沒有提供程序XHRBackend

HTTP .service.ts

import { Injectable } from '@angular/core'; 
import { Http, XHRBackend, RequestOptions, RequestOptionsArgs, Request, Response } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 


@Injectable() 
export class HttpService extends Http { 
    constructor(backend: XHRBackend, options: RequestOptions) { 
     console.log('HttpService constructor'); 
     super(backend, options); 
    } 

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { 
     console.log('HttpService request'); 
     return super.request(url, options); 
    }  
} 

export const HTTP_SERVICE = { 
    provide: HttpService, 
    useFactory: (backend: XHRBackend, options: RequestOptions) => { 
     return new HttpService(backend, options); 
    }, 
    deps: [XHRBackend, RequestOptions] 
}; 

然後我在app.module.ts

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

import { AppRoutingModule } from './app-routing.module'; 

import { AppComponent } from './app.component'; 

import { AuthService } from './auth/auth.service'; 
import { HTTP_SERVICE } from './shared/http/http.service'; 

@NgModule({ 
    imports: [ 
     BrowserModule, 
     AppRoutingModule 
    ], 
    declarations: [ 
     AppComponent 
    ], 
    providers: [ 
     AuthService, 
     HTTP_SERVICE 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

增加,但是當我把它注射到一個組件構造它不工作。我收到提到的錯誤。

我也看了,我可以這樣做:

{ provide: Http, useClass: HttpService} 

從這個博客:http://www.adonespitogo.com/articles/angular-2-extending-http-provider/

但這也不起作用。在這裏我沒有錯誤,但沒有什麼不同。正如我期望的那樣,我沒有輸出到控制檯。

我也試着只是加上HttpService,因爲它在providers數組中,仍然有這個錯誤。

+3

您可以將'HttpModule'添加到'imports'以獲取它已經定義的提供者。那麼你不需要'HTTP_SERVICE'和*可以*只使用博客中的簡單提供者。 – jonrsharpe

+1

可能重複[沒有提供程序的ConnectionBackend而從Http繼承](http://stackoverflow.com/questions/40507670/no-provider-for-connectionbackend-while-inheriting-from-http) – jonrsharpe

+0

我有同樣的問題,但沒有解決辦法,你有沒有找到? –

回答

0

Mukul Jayaprakash所述,在您的imports中加入httpModule即可解決此問題。

相關問題