Angular2 - 将http注入自定义服务

时间:2016-10-04 08:13:59

标签: angular angular2-services angular2-modules

我构建了一个 ErrorHandlerLogger ,这是一个扩展ErrorHandler并将错误消息记录到远程存储库的服务。

ErrorHandlerLogger 需要 HttpModule 提供的Angular http 客户端。

ErrorHandlerModule 中,我导入 HttpModule 并将 ErrorHandlerLogger 定义为提供者。

AppModule 中,我导入 ErrorHandlerModule

当我启动应用程序时,我收到以下错误消息

Uncaught Error: Can't resolve all parameters for ErrorHandlerLogger: (?).

这是我的代码

ErrorHandlerModule

import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';

import {ErrorHandlerLogger} from './error-handler-logger';

@NgModule({
    declarations: [],
    exports: [],
    imports: [
        HttpModule
    ],
    providers: [
        {provide: ErrorHandler, useClass: ErrorHandlerLogger}
    ]
})
export class ErrorHandlerModule {}

ErrorHandlerLogger

import { ErrorHandler } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';
import './rxjs-operators';

export class ErrorHandlerLogger extends ErrorHandler {
    constructor(private http: Http) {
        super();
     }

    handleError(error) {
        // my logic
    }

}

的AppModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {ErrorHandlerModule} from './error-manager/error-handler.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    ErrorHandlerModule
  ],
  providers: [appRoutingProviders],
  bootstrap: [AppComponent]
})
export class AppModule { }

非常感谢任何帮助

1 个答案:

答案 0 :(得分:65)

@Injectable() // <<<=== required if the constructor has parameters 
export class ErrorHandlerLogger extends ErrorHandler {