【发布时间】:2021-08-26 04:44:32
【问题描述】:
我的应用程序中有很多地方需要以相同的方式处理失败的异步方法调用:显示烤面包机并在控制台中记录错误。为此,我正在为 Angular 控制器方法编写一个装饰器。假设该方法是一个异步函数,例如:
@ToastOnFail
async makeCall() {
const result = await this.httpService.makeSomeRequest();
// do stuff with the result
}
我的装饰器看起来像这样
export default async function ToastOnFail(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
const toasterService = AppModule.injector.get<ToasterService>(
ToasterService as Type<ToasterService>
);
return originalMethod.apply(this, args)
.catch((err) => {
toasterService.addGenericActionIncompleteError();
console.error(err);
});
};
}
我得到一个编译错误
错误 TS1241:当作为表达式调用时,无法解析方法装饰器的签名。 “Promise”类型与“TypedPropertyDescriptor Promise>”类型没有共同的属性。
我不确定是否是 TS 混淆,我必须进行一些手动转换,或者我是否没有返回我应该从装饰器返回的内容。我错过了什么?
【问题讨论】:
-
这似乎在这里得到了回答 - stackoverflow.com/a/58507238/222090
标签: angular typescript decorator angular-decorator