为什么 Angular 没有为 HttpClient.get(...) 选择正确的重载? [英] Why is Angular not choosing correct overload for HttpClient.get(...)?
问题描述
我正在尝试将一些 HttpClient 调用(.get(...) 和 .post(...))抽象到一个 BaseService 类中,因为如果我的服务,我必须复制标头和凭据等代码不要从基类继承.
I'm trying to abstract out some HttpClient calls (.get(...) and .post(...)) into a BaseService class since I'm having to duplicate code such as headers and credentials if my services don't inherit from a base class.
这样做时,出于某种原因,我的代码没有选择 get 上的通用重载.
In doing this, for some reason my code isn't choosing the generic overload on the get.
以下方法调用成功选择了正确的 HttpClient.get(...) 重载:
The following method call is successfully choosing the correct HttpClient.get(...) overload:
但是,以下是选择不同的重载,我不知道如何解决它:
However, the following is choosing a different overload, and I have no idea how to fix it:
这是因为我错误地声明了私有选项字段吗?我在 API 文档中找不到更好/正确的声明方式,以便成功选择正确的重载.有人可以帮我让我的代码为 HttpClient.get(...) 选择正确的(通用 Observable
)重载吗?
Is this because I'm declaring the private options field incorrectly? I can't find in the API docs a better/correct way of declaring it so that the correct overload will be chosen successfully. Can someone please help me make my code choose the correct (generic Observable<T>
) overload for HttpClient.get(...)?
推荐答案
这是因为您要声明类型为 any
的选项.
This is because you are declaring options with type any
.
通过这样做,编译器一无所知options
的接口/成员,尽管您使用由 2 个属性组成的对象实例化其值.
By doing this, the compiler knows nothing about the interface/members of options
, despite the fact that you instantiate its value with an object made of 2 properties.
重构为:
export class Foo {
private options = {headers: {...}, withCredentials: true};
....
}
现在编译器可以推断options
的类型,而不是静态读取它.
Now the compiler can infer the type of options
, instead of statically reading it.
这篇关于为什么 Angular 没有为 HttpClient.get(...) 选择正确的重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!