在 Angular 14 中,是否可以将拦截器应用于抽象类型的对象?

问题描述 投票:0回答:1

我正在使用 Angular 14。我有一个抽象模型

export class AbstractMyModel {
    constructor(public commonProperty: string) {
    }
}

其他模型将从中扩展。有没有办法编写一个拦截器(或其他类似函数)来拦截使用 httpclient 提交的“put”和“post”调用并转换抽象模型的“commonProperty”字段?也就是说,对于像

这样的电话
return this.httpClient.post<MyResponse>(
  `${url}`,
  child
);

其中子项属于扩展“AbstractMyModel”的类型,我想将一个函数应用于子属性“commonProperty”,以便进行与以下调用等效的

return this.httpClient.post<MyResponse>(
  `${url}`,
  {
...child,
    commonProperty: transformFn(child.commonProperty)
  }
);
angular httpclient interceptor abstract angular14
1个回答
0
投票

我认为你应该能够用香草

instanceof
operator 做到这一点,因为
AbstractMyModel.prototype
应该出现在任何
class Foo extends AbstractMyModel
的原型链中。

像往常一样设置一个拦截器,检查它接收到的请求的方法和主体,然后执行你需要的任何逻辑。

import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { AbstractMyModel, transformFn } from '../models/abstract-my.model';

const supportedMethods = ['PUT', 'POST'];

export class MyModelInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    // Short circuit if the request doesn't match
    // our criteria.
    const methodUnsupported = !supportedMethods.some(m => request.method === m);
    const bodyTypeUnsupported = !(request.body instanceof AbstractMyModel);
    
    if (methodUnsupported || bodyTypeUnsupported) {
      return next.handle(request);
    }

    // Otherwise perform whatever logic we need.
    const commonProperty = transformFn(request.body.commonProperty);
    const newBody = { ...request.body, commonProperty };
    const newRequest = request.clone({ body: newBody });

    return next.handle(newRequest);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.