[英]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?为什么我必须在案例 1 中传递参数,而在案例 2 中则不需要? And how to solve my problem?
以及如何解决我的问题?
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
依赖注入 (DI) 是一种设计模式,其中类从外部源请求依赖而不是创建它们
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!我建议你看一下 Angular 的官方文档,总是很清楚而且很有用!
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 ;如果您只需要使用 HttpClient,请按照
// Case 2
进行操作,无需初始化任何内容; 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 ;)如果您有任何疑问,请告诉我;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.