Angular 2 custom HTTP service throws Error: No provider for XHRBackend

I wanted to create my own http service to use as an http interceptor, but I get a very long error that starts with: 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]
};

      

And then add it to 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 { }

      

But it doesn't work when I insert it into the constructor in the component. I am getting the mentioned error.

I also read what I can do:

{ provide: Http, useClass: HttpService}

      

from this blog: http://www.adonespitogo.com/articles/angular-2-extending-http-provider/

But that doesn't work either. I am not mistaken here, but nothing has changed. I am not getting console output as I expect from the code.

I also tried to just add HttpService

as in the providers array, still got this error.

+3


source to share


1 answer


How Mukul Jayaprakash added httpModule

to yours imports

will solve this problem.



0


source







All Articles