简体   繁体   English

无法实现方法装饰器来捕获 Angular 中的 http 错误?

[英]Not able to implement method decorators for catching http errors in Angular?

Actually I want to catch errors on all http requests using custom decorators.实际上,我想使用自定义装饰器捕获所有 http 请求的错误。

My actual code looks like this:我的实际代码如下所示:

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

I want to convert these kind of functions to something like this:我想将这些函数转换成这样的:

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

I know this is possible using http interceptors but I tried it using custom method decorators.我知道使用 http 拦截器可以做到这一点,但我使用自定义方法装饰器进行了尝试。 My decorator looks like this:我的装饰器看起来像这样:

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;
    };
  }

And then I decorate the function like this:然后我像这样装饰 function:

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

But the problem here is that it tries to execute the function then only when I initialize this particular service, not when I actually call createRecord method.但这里的问题是它尝试执行 function 只有当我初始化这个特定服务时,而不是当我实际调用 createRecord 方法时。 How do I modify the method decorator to achieve this result?如何修改方法装饰器以实现此结果?

If you want the decorator to alter the behavior of the method it's applied on, you need to override the original method from within the decorator:如果你希望装饰器改变它所应用的方法的行为,你需要从装饰器中覆盖原始方法:

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)
            );
      }
}

Note that it's important to define the override with the function keyword and not an arrow function to be able to use the this of the class context.请注意,使用function关键字而不是箭头 function 定义覆盖非常重要,以便能够使用 class 上下文的this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM