首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular12 -截取graphql HTTP请求和响应

Angular12 -截取graphql HTTP请求和响应
EN

Stack Overflow用户
提问于 2021-09-22 13:53:11
回答 2查看 66关注 0票数 0

因此,我们有了Graphql响应处理程序

代码语言:javascript
复制
export const handleResponse = (operation: DocumentNode): OperatorFunction<any, any> => {
  return pipe(
    map((response: any) => {
      const definition = operation.definitions[0] as OperationDefinitionNode;
      const selection = definition.selectionSet.selections[0] as FieldNode;
      const selectionName = selection.name.value ?? null;
      if (!selectionName) {
        throw new Error(`${selection.kind} name must be present.`);
      }
      if (response.data[selectionName]?.errors) {
        handleError(response.data[selectionName].errors);
      }
      return response.data[selectionName];
    }),
  );
};

const handleError = (errors: string[]) => {
  if (Array.isArray(errors) && errors.length) {
    const errorArrayToString = errors.map(error => JSON.stringify(error)).toString();
    throw new Error(errorArrayToString);
  }
};

它确实工作得很好,但我也想使用通知服务。我想做这样的事情

代码语言:javascript
复制
const handleError = (errors: string[]) => {
  if (Array.isArray(errors) && errors.length) {

    notificationsService.show('Any error message')

    const errorArrayToString = errors.map(error => JSON.stringify(error)).toString();
    throw new Error(errorArrayToString);
  }
};
EN

回答 2

Stack Overflow用户

发布于 2021-09-22 14:28:04

您需要将服务注入到变量中

代码语言:javascript
复制
import { Component, Injector, OnInit } from '@angular/core';
import { NotificationsService } from './custom.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {

  // @Constructor services injectors

  notificationsService: NotificationsService;

  /**
   * Constructor
  */
  constructor(
    private _injector: Injector
  ) {
    this.notificationsService = this._injector.get<NotificationsService>(NotificationsService);
}

 ngOnInit(): void {
 }

 //custom error handler
 handleError (errors: string[]) => {
  if (Array.isArray(errors) && errors.length) {

    this.notificationsService.show('Any error message')

    const errorArrayToString = errors.map(error => JSON.stringify(error)).toString();
    throw new Error(errorArrayToString);
  }
};
}
票数 0
EN

Stack Overflow用户

发布于 2021-09-23 12:34:32

谢谢,但我决定将此逻辑转移到HTTP拦截器中。以下是代码

代码语言:javascript
复制
@Injectable()
export class ApolloErrorInterceptor implements HttpInterceptor {
  constructor(private _notificationsService: TuiNotificationsService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap((response: any) => {
        if (request.body?.operationName) {
          const operationName = request.body.operationName;

          if (response.body?.data[operationName]?.errors) {
            response.body.data[operationName].errors.forEach((error: any) => {
              this._notificationsService
                .show(error.message, { status: TuiNotification.Error, autoClose: 5000 })
                .subscribe();
            });
          }
        }
      }),
    );
  }
}

它将只拦截正文中具有"operationName“的响应,即Graphql响应

但是现在您需要显式地确保指定请求的名称

query examplemutation example

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69285670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档