Angular 2 DI, use custom Http

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 the 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){}
      ....
}

It works. I have commented text {specify: Http, useClass: Http}. I want to provide my own class here, which extends Http, but still has the same dependencies. The first step I take here is to explicitly use Http.

As soon as I don’t comment on this text (and add the HTTP import), everything breaks. I get an error message"No provider for ConnectionBackend" . It seems that HTTP_PROVIDERS just stopped working as a provider.

  • How can I use this use of Http?
  • How to use your own CustomHttp and use providers in HTTP_PROVIDERS?
+4
3

CustomHttp HTTP_PROVIDERS, ( .module.ts, RC5 main.ts, RC4):

providers: [
    ConnectionBackend,
    provide(
        Http, {
            useFactory: (
                backend: XHRBackend,
                defaultOptions: RequestOptions) =>
                new CustomHttp(backend, defaultOptions),
            deps: [XHRBackend, RequestOptions]
        }),
]

, .

Edit:

HTTP_PROVIDERS, RC5, HttpModule, , HTTP_PROVIDERS RC4. , .

+2

Angular 2.1.1 , angular2 . , Http app.module.ts

export function httpFactory(backend: XHRBackend, defaultOptions: RequestOptions) {
  return  new CustomHttp(backend, defaultOptions);
}

...

providers:    [
               {provide: Http, 
                         useFactory: httpFactory,
                         deps: [XHRBackend, RequestOptions]
               }
              ]

angular2 : https://angular.io/docs/ts/latest/api/http/index/XHRBackend-class.html

CustomHttp, , , .

CustomHttp angular2, , , .

+4

If you do not want to change the XHRBackend and RequestOptions implementations, you can make this simpler:

providers: [
    {provide: Http, useClass: MyCustomHttp}
]
+2
source

Source: https://habr.com/ru/post/1652195/


All Articles