我正在尝试在使用 Angular DI (ngx) 的 node.js 应用程序中注入(inject) Superagent。
import * as request from 'superagent';
...
{
provide: request,
useFactory: () =>
request.agent()
.timeout({deadline: 10000, timeout: 60000}),
},
但我得到 property
超时 does not exist on SuperAgent<SuperAgentRequest>
.我尝试关注 these docs但 SuperAgent 似乎不是正确的类型。 request.agent()
的类型应该是 request.Request
.
我错过了什么?如何正确提供 request.Request
以便我可以全局配置它以使用相同的(注入(inject)的)实例?
最佳答案
从 Superagent 类型中可以看出,request.agent()
返回 SuperAgent<SuperAgentRequest>
that doesn't have timeout
method ,这就是错误信息所说的。
同时 timeout
Request
中存在方法类型是响应的 promise 。这就是引发此错误的原因。没有请求也没有回应。 Superagent documentation为 timeout
提供示例:
request
.get('/big-file?network=slow')
.timeout({
response: 5000, // Wait 5 seconds for the server to start sending,
deadline: 60000, // but allow 1 minute for the file to finish loading.
})
文档指出代理实例有 methods that set defaults ,所以缺少打字。没有 deadline
方法,它对 timeout
没有意义,因为这是最后期限超时。
superagent
类型应该在本地增加,或者改进并 PRed 到 DefinitelyTyped 存储库,或者就地固定:
{
provide: request,
useFactory: () =>
<SuperAgent<SuperAgentRequest>>request.agent()
['timeout'](30)
}
我希望增强类型类似于(处理原始 Request
接口(interface)与正则表达式):
custom.d.ts
import * as request from 'superagent';
type CallbackHandler = (err: any, res: request.Response) => void;
type Serializer = (obj: any) => string;
type BrowserParser = (str: string) => any;
type NodeParser = (res: request.Response, callback: (err: Error | null, body: any) => void) => void;
type Parser = BrowserParser | NodeParser;
declare module "superagent" {
interface ConfigurableSuperAgent<Req extends request.SuperAgentRequest> extends request.SuperAgent<Req> {
accept(type: string): this;
auth(user: string, name: string): this;
buffer(val?: boolean): this;
ca(cert: Buffer): this;
cert(cert: Buffer | string): this;
key(cert: Buffer | string): this;
ok(callback: (res: Response) => boolean): this;
on(name: 'error', handler: (err: any) => void): this;
on(name: 'progress', handler: (event: ProgressEvent) => void): this;
on(name: string, handler: (event: any) => void): this;
parse(parser: Parser): this;
pfx(cert: Buffer | string): this;
query(val: object | string): this;
redirects(n: number): this;
retry(count?: number, callback?: CallbackHandler): this;
serialize(serializer: Serializer): this;
set(field: object): this;
set(field: string, val: string): this;
timeout(ms: number | { deadline?: number, response?: number }): this;
type(val: string): this;
use(fn: Plugin): this;
}
interface SuperAgentStatic extends request.SuperAgent<request.SuperAgentRequest> {
agent(): ConfigurableSuperAgent<request.SuperAgentRequest>;
}
}
关于javascript - Angular DI 注入(inject)的 super 代理的正确类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50340305/