【问题标题】:showing MatSnackBar message when Apollo GraphQL fails with an error当 Apollo GraphQL 失败并出现错误时显示 MatSnackBar 消息
【发布时间】:2020-12-22 21:52:34
【问题描述】:

我有一个使用 Angular 10 和 Apollo GraphQL 的网站。

每当请求失败时,我想向使用MatSnackBar 的用户显示错误,但我不知道如何将MatSnackBar 组件提供给OnError()OnError() 函数apollo-link-error

这是我的graphql.module.ts 代码:

import {NgModule} from '@angular/core';
import {APOLLO_OPTIONS} from 'apollo-angular';
import {ApolloClientOptions, ApolloLink, InMemoryCache} from '@apollo/client/core';
import {HttpLink} from 'apollo-angular/http';
import { onError } from 'apollo-link-error';

function getNewToken(): any {
  //TODO: need to implement
}

const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
    if (graphQLErrors) {
      for (const err of graphQLErrors) {
        switch (err.extensions?.code) {
          case 'UNAUTHENTICATED':
            // error code is set to UNAUTHENTICATED
            // when AuthenticationError thrown in resolver

            // modify the operation context with a new token
            const oldHeaders = operation.getContext().headers;
            operation.setContext({
              headers: {
                ...oldHeaders,
                authorization: getNewToken(),
              },
            });
            // retry the request, returning the new observable
            return forward(operation);
        }
      }
      graphQLErrors.map(({ message, locations, path }) =>
        console.log(
          `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
        ),
      );
    }

    if (networkError) {
      console.log(`[Network error]: ${networkError}`);
      // if you would also like to retry automatically on
      // network errors, we recommend that you use
      // apollo-link-retry
    }
  }
);

const uri = 'http://localhost:8081/graphql';
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  const httpLinkHandler = httpLink.create({uri});
  const httpLinkWithErrorHandling = ApolloLink.from([
    // @ts-ignore
    errorLink,
    httpLinkHandler,
  ]);

  return {
    link: httpLinkWithErrorHandling,
    cache: new InMemoryCache(),
  };
}

@NgModule({
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

使用console.info 在哪里显示错误?我想展示一个小吃店。有什么想法吗?

【问题讨论】:

  • 链接不用于渲染(它不是php,你可以在任何地方echo "error"; die;)...它是请求/响应处理的一部分,链...响应必须到达客户端...应用程序与客户端合作会获取错误信息 - 在应用层中使用此信息......使用 axios 会如何?
  • @xadm - 我可以在工具栏中订阅事件并从这里发送事件,以便工具栏捕获它并显示那个 mat-snackbar 吗?
  • 抱歉,IDK,不与 Ang 合作。

标签: angular angular-material graphql apollo


【解决方案1】:

我在创建赏金后不久就找到了解决方案。所以只需注入MatSnackbar,将其复制到一个局部变量中以在错误对象中使用。

所以在提供程序依赖项中,我将MatSnackBar 添加到依赖项中:

@NgModule({
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: createApollo,
      deps: [HttpLink, MatSnackBar],
    },
  ],
})
export class GraphQLModule {}

然后在createApollo() 函数中,我将matSnackBar 复制到了一个局部变量中:

export function createApollo(httpLink: HttpLink, matSnackBar: MatSnackBar): ApolloClientOptions<any> {
      localMatSnackbar = matSnackBar;

然后在onError() 处理程序中我在网络错误上使用它:

if (networkError) {
  localMatSnackbar?.open(networkError.message, 'DISMISS', {
    duration: 2000,
    verticalPosition: 'top'
  });

就是这样!

如果有更优雅的方法来解决它,我将非常乐意接受不同的答案。

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2021-07-31
    • 2019-11-01
    • 2015-03-17
    • 2012-11-26
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    相关资源
    最近更新 更多