问题描述
我正在尝试将一些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<T>
)重载吗?
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
.
这样做,尽管您使用由2个属性组成的对象实例化了它的值,但是编译器对options
的接口/成员一无所知.
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(...)选择正确的重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!