【问题标题】:Not able to implement method decorators for catching http errors in Angular?无法实现用于在 Angular 中捕获 http 错误的方法装饰器?
【发布时间】:2021-06-09 11:11:51
【问题描述】:

实际上我想使用自定义装饰器捕获所有 http 请求的错误。

我的实际代码如下所示:

  createRecord(data: data) {
    
    return this.httpClient.post(`${this.apiURL}/record/`, data);
  }

我想把这些函数转换成这样的:

 createRecord(data: data) {
        
        return this.httpClient.post(`${this.apiURL}/record/`, data)
               .pipe(tap((data)=>console.log(data)),catchError(handleError)));
      }

我知道使用 http 拦截器可以做到这一点,但我使用自定义方法装饰器进行了尝试。 我的装饰器看起来像这样:

export function CatchHttpError() : MethodDecorator {
    return function ( target : any, propertyKey : string, descriptor : PropertyDescriptor ) {
      const original = descriptor.value;
      descriptor.value = original()
      .pipe(
        tap((data)=>console.log('tap entered: data = ',data)),
        catchError(handleError)
      );
      return descriptor;
    };
  }

然后我像这样装饰函数:

 @CatchHttpError()
  createRecord(data: data) {
    
    return this.httpClient.post(`${this.apiURL}/record/`, data);
  }

但这里的问题是,它仅在我初始化此特定服务时才尝试执行该函数,而不是在我实际调用 createRecord 方法时。如何修改方法装饰器来达到这个效果?

【问题讨论】:

    标签: angular typescript angular2-decorators


    【解决方案1】:

    如果你想让装饰器改变它所应用的方法的行为,你需要在装饰器中覆盖原来的方法:

    export function CatchHttpError() : MethodDecorator {
        return function (target : any, propertyKey : string, descriptor : PropertyDescriptor ) {
          const original = descriptor.value;
          // override the method
          descriptor.value = function(...args: any[]) {
                // Calling the original method
                const originalResults = original.apply(this, args);
                return originalReults.pipe(
                    tap((data) => console.log('tap entered: data = ',data)),
                    catchError(handleError)
                );
          }
    }
    

    请注意,使用 function 关键字而不是箭头函数定义覆盖非常重要,以便能够使用类上下文的 this

    【讨论】:

      猜你喜欢
      • 2013-02-25
      • 2019-01-20
      • 2019-07-12
      • 2018-09-12
      • 2013-02-14
      • 2018-05-14
      • 2023-03-16
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多