【发布时间】: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