我想创建自己的http服务,以便我可以像http拦截器一样使用它但是我得到一个很长的错误,它始于:EXCEPTION: Uncaught (in promise): Error: No provider for 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
,但仍然出现错误。