我正在尝试扩展Angular 2 http类以处理全局错误并设置头信息用于我的secureHttp服务。我找到了一些解决方案,但这些解决方案不适用于Angular 2的最终版本。 这是我的代码:
文件:secureHttp.service.ts
import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, Headers, RequestOptions, Response, RequestOptionsArgs} from '@angular/http';
@Injectable()
export class SecureHttpService extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
}
文件: app.module.ts
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { routing } from './app.routes';
import { AppComponent } from './app.component';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http';
import { CoreModule } from './core/core.module';
import {SecureHttpService} from './config/secure-http.service'
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
CoreModule,
routing,
HttpModule,
],
providers: [
{
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => {
return new SecureHttpService(backend, defaultOptions);
},
deps: [ XHRBackend, RequestOptions]
}, Title, SecureHttpService],
bootstrap: [AppComponent],
})
export class AppModule { }
组件.ts
constructor(private titleService: Title, private _secure: SecureHttpService) {}
ngOnInit() {
this.titleService.setTitle('Dashboard');
this._secure.get('http://api.example.local')
.map(res => res.json())
.subscribe(
data => console.log(data) ,
err => console.log(err),
() => console.log('Request Complete')
);
}
目前它返回了一个错误:“没有ConnectionBackend提供程序!” 感谢帮助!
{provide: HttpService, useFactory: ()},
代码处遇到了 "Expression expected." 错误。 - Pavel Chuchuva