【问题标题】:Angular promise handling decorator on an async method异步方法上的 Angular 承诺处理装饰器
【发布时间】: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 混淆,我必须进行一些手动转换,或者我是否没有返回我应该从装饰器返回的内容。我错过了什么?

【问题讨论】:

标签: angular typescript decorator angular-decorator


【解决方案1】:

免责声明这不是您问题的答案

为什么不使用“自定义运算符”? here 有一个关于自定义运算符的很棒的链接。通过这种方式,您可以对可观察对象“采取行动”

有人喜欢

function debug<T>(toasterService:ToasterService) {
  return function<T>(source: Observable<T>): Observable<T> {
    return source.pipe(catchError((err:any)=>{
      toasterService.addGenericActionIncompleteError()
      return throwError(err) //or return of(null)
    }));
  };
}

允许你写

const result = this.httpService.makeSomeRequest().pipe(debug(this.myToaster));

【讨论】:

  • 说实话我用过其他装饰器来装饰应用程序的各个部分,具有各种不同的行为,我想继续练习,我个人觉得它更干净。事情是根本不编辑原始方法,装饰器很容易打开/关闭,可单独测试等。
猜你喜欢
  • 2019-07-22
  • 2022-11-03
  • 2020-03-22
  • 2019-03-27
  • 2017-01-22
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
相关资源
最近更新 更多