Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate an Angular HttpClient?

How do you instantiate an HttpClient in Angular 5? I need to instantiate it inside the constructor, but not in this line constructor(private _Http: HttpClient).

Maybe something like this hypothetical example:

import { HttpClient, HttpHandler } from '@angular/common/http';
private _Http: HttpClient;
private _httpHandler: HttpHandler;
@Injectable()
export class DataService {
    constructor() {
        this._Http = new HttpClient(_httpHandler);
    }
}

Thank you

like image 381
Marcelo Varela da Silva Avatar asked Jan 21 '18 21:01

Marcelo Varela da Silva


1 Answers

As previous answers stated, it's better to use dependency injection. That's being said, you can create instance manually like below

const httpClient = new HttpClient(new HttpXhrBackend({ 
    build: () => new XMLHttpRequest() 
}));
like image 114
mtareq Avatar answered Sep 20 '22 02:09

mtareq