简体   繁体   中英

Why does constructor of HttpClient in Angular not need param, when I instanstiate it via constructor of other class, but needs via new?

I need to make a static method for instanstiating an object of class, but faced an issue.

import { HttpClient } from '@angular/common/http';

export MyClass {
  // Case 1
  public static init(): MyClass {
    return this(new HttpClient(***), ....); // Need to pass new HttpClient() instead ***
  }

  // Case 2
  public constructor(private http: HttpClient, ....) {} // Need to pass nothing
}

Why I have to pass argument in case 1, but in case 2 not? And how to solve my problem?

Answer

This happens thanks to dependency injection . Angular says:

Dependency injection, or DI, is a design pattern in which a class requests dependencies from external sources rather than creating them

In your case you don't need to "create" that resource but simply use it, and for that dependency injection comes to your aid

I recommend you take a look at the official documentation of Angular, always very clear and quite useful!

And how to solve my problem?

If you just need to use HttpClient, do as in // Case 2 and without the need to initialize anything ; otherwise, if you can please explain better what your goal is and how you can't achieve it so we can help you, thanks!


Let me know if you have any doubts ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM