因此,我们有了Graphql响应处理程序
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);
}
};它确实工作得很好,但我也想使用通知服务。我想做这样的事情
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);
}
};发布于 2021-09-22 14:28:04
您需要将服务注入到变量中
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);
}
};
}发布于 2021-09-23 12:34:32
谢谢,但我决定将此逻辑转移到HTTP拦截器中。以下是代码
@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响应
但是现在您需要显式地确保指定请求的名称
https://stackoverflow.com/questions/69285670
复制相似问题