当Apollo GraphQL失败并显示错误时显示MatSnackBar消息

时间:2020-09-03 15:55:01

标签: angular angular-material graphql apollo

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

每当请求失败时,我都想使用MatSnackBar向用户显示错误,但是我不知道如何为{的MatSnackBar函数提供OnError()组件{1}}。

这是我的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 {} 在哪里显示错误?我想展示一个小吃店。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

创建赏金后不久,我找到了解决方案。因此,只需注入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'
  });

就是这样!

如果有更优雅的解决方法,我很乐意接受其他答案。