I have a service that uses Http:
import { Injectable } from '@angular/core';
import { Inject } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
@Injectable()
export class OrdersService {
constructor(@Inject(Http) private http:Http) {}
...
}
And a component that uses it
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';
import { HTTP_PROVIDERS } from '@angular/http';
import { Router} from '@angular/router';
import { OrdersService } from '../services/orders.service'
@Component({
selector: 'login',
templateUrl: './login.component.html',
providers: [
HTTP_PROVIDERS, //{ provide: Http, useClass: Http }
AuthService, AuthStore,
OrdersService
]
})
export class LoginComponent {
constructor(private authService: AuthService, private ordersService: OrdersService){}
....
}
This works. I have some commented out text { provide: Http, useClass: Http }. I want to provide my own class here that extends Http, but still has all the same dependancies. The first step I'm taking here is to explicitly use Http.
As soon as I un-comment this text (and add an http import), everything breaks. I get the error "No provider for ConnectionBackend"
. It appears that HTTP_PROVIDERS has just stopped working as a provider.
From Angular 2.1.1 and above syntax for provide option was changed after angular2 team introduce new modules concept. Below you will find correct syntax how to add your own custom provider for Http in your app.module.ts
export function httpFactory(backend: XHRBackend, defaultOptions: RequestOptions) {
return new CustomHttp(backend, defaultOptions);
}
...
providers: [
{provide: Http,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions]
}
]
You can also verify the angular2 documentation here: https://angular.io/docs/ts/latest/api/http/index/XHRBackend-class.html
If you want to implement you own CustomHttp class I will recommend you to read Thierry Templier article when step by step he is introducing how to do that.
Implementing CustomHttp for angular2 this is very helpful article which is describing how to extend to intercept request calls and add custom handling errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With