How to instantiate HttpClient in Angular typescript 4?

0

Based on this example for Http, I would like to know how to instantiate HttpClient:

 **constructor() {  
    const browserXhr: BrowserXhr = new BrowserXhr();  
    const baseResponseOptions: ResponseOptions = new ResponseOptions();  
    const xsrfStrategy: CookieXSRFStrategy = new CookieXSRFStrategy();  
    const backend: XHRBackend = new XHRBackend(browserXhr, baseResponseOptions, xsrfStrategy);  
    const requestOptions: RequestOptions = new RequestOptions();  
    const http: Http = new Http(backend, requestOptions);  
this._http = http;**  

So I would like to know how to instantiate HttpClient this way.

I have a class and I have a class parameter.

More current considerations ...

I need to create a class that when instantiated I will tell the name of the table that it will work but I do not want to have the need to enter more parameters in the class constructor as I have to do currently as this example below (this is how it works now ):

@Injectable() 
export class MvsDbTable implements OnInit {
constructor( 
    @Inject('_tableName') public _tableName: string, 
    @Inject('_HTTP') public _HTTP: HttpClient  ) {}

Then I instantiate the class in a service:

    public _tblFinances = new MvsDbTable('Finances', this._Http);

But I would like to not have to report this parameter, "this.http".

So I'd like it to look like this:

@Injectable() 
export class MvsDbTable implements OnInit {
constructor( 
    @Inject('_tableName') public _tableName: string ) {
    this._HTTP = new HttpClient(this._Handler);   }     

It just does not work to instantiate the _Handler parameter because it is abstract so it can not be instantiated.

So I would instantiate the class in a service like this:

    public _tblFinances = new MvsDbTable('Finances');

Just the code is cleaner, the first form already works. What I try to figure out is how to instantiate the HttpClient inside the class without having to pass the HttpClient as a parameter in the constructor as I did with the Http that also worked.

Thank you

    
asked by anonymous 14.08.2017 / 23:17

1 answer

0

Within the app.module.ts you can define how the provider will be instantiated.

Create an object informing the class that will be provided, the method that will make new (useFactory) and the dependencies needed to create your class (deps):

import { FactoryProvider } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHandler } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    <FactoryProvider>{
      provide: HttpClient, HttpClient ou sua classe que herda HttpClient
      useFactory: requestLoader,
      deps: [ HttpHandler ]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

export function requestLoader(handler: HttpHandler) {
  return new HttpClient(handler); // HttpClient ou sua classe que herda HttpClient
}

This way you can use the constructor by asking for the HttpClient service or your class that inherits HttpClient

Important: If your goal is to intercept requests to enter authorization tokens, for example, this is no longer the best way to do it from angle 4.3.4. For this you must use interceptors (Example based on article building-http-interceptor-angular-5 ):

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyHttpInterceptor } from './myhttp.interceptor';

import { AppComponent } from './app.component';

@NgModule({
declarations: [
    AppComponent,
],
imports: [
    BrowserModule,
    HttpClientModule
],
providers: [
    {
    provide: HTTP_INTERCEPTORS,
    useClass: MyHttpInterceptor,
    multi: true
    }
],
bootstrap: [AppComponent]
})
export class AppModule { }

myhttp.interceptor.ts:

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // logar para teste
        console.log('intercepted request ... ');

        // Clonar a requisição para adicionar o cabeçalho
        const authReq = req.clone(
            {
                headers: req.headers.set('headerName', 'headerValue')
            }
        );

        console.log('Sending request with new header now ...');

        // enviar a requisição modificada para a proxima classe da cadeia
        return next.handle(authReq)
            .catch((error, caught) => {
                // interceptar a resposta de erro e logar
                console.log('Error Occurred');
                console.log(error);
                // returnar o erro para o metodo que chamou
                return Observable.throw(error);
            }) as any;
    }
}
    
17.10.2017 / 03:56