Angular 4: What is the benefit of HttpClient injection

After Angular docs , HttpClientis introduced into the component app. I saw on another guide that it was “profitable” without explanation.

@Component(...)
export class MyComponent implements OnInit {

  results: string[];

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}

On this I have a few questions:

1) Where/How is the HttpClient actually instantiated?  Does `ng serve` handle this?
2) How could I inject a different instance if I needed to?
+1
source share
3 answers

If you want to use a service (which mainly belongs to the TS class), you must first create it. This is what the angular injector does for you automatically.

This approach is “favorable” because it automatically searches for service dependencies defined in its constructor.

, - (), .

angular :

https://angular.io/guide/dependency-injection

+2

, HttpClient - Http. Http Angular 5 .

, ""? . , Angular.

Http, HttpClient , , Http.

, . , ?

+1

HttpClient/HttpClientModule, ng 4.3+, Http/HttpModule. , () GET JSON, , , , /. , , cli npm, , , , ! , , .

enter image description here

+1

All Articles