gpt4 book ai didi

angular - 当 Apollo GraphQL 失败并出现错误时显示 MatSnackBar 消息

转载 作者:行者123 更新时间:2023-12-03 23:44:30 25 4
gpt4 key购买 nike

我有一个使用 Angular 10 和 Apollo GraphQL 的网站。
每当请求失败时,我想向用户显示错误使用 MatSnackBar ,但我不知道如何提供 MatSnackBar 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 显示错误? ?我想展示一个 snackbar 。有任何想法吗?

最佳答案

创建赏金后不久,我找到了解决方案。所以只需注入(inject) 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'
});
就是这样!
如果有更优雅的方法来解决它,我将非常乐意接受不同的答案。

关于angular - 当 Apollo GraphQL 失败并出现错误时显示 MatSnackBar 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63727362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com