在Angular for GraphQL中使用Apollo客户端处理错误的方法如下:
apollo-angular
和apollo-angular-link-http
这两个包。可以使用以下命令进行安装:npm install apollo-angular apollo-angular-link-http
ng generate service graphql
import { Injectable } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { ApolloClient, InMemoryCache } from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
import { onError } from '@apollo/client/link/error';
@Injectable({
providedIn: 'root'
})
export class GraphqlService {
private apolloClient: ApolloClient<any>;
constructor(private apollo: Apollo, private httpLink: HttpLink) {
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) => {
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
);
});
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});
const httpLinkWithMiddleware = errorLink.concat(httpLink.create({ uri: 'YOUR_GRAPHQL_ENDPOINT' }));
this.apolloClient = new ApolloClient({
link: httpLinkWithMiddleware,
cache: new InMemoryCache()
});
this.apollo.setClient(this.apolloClient);
}
}
请注意,你需要将YOUR_GRAPHQL_ENDPOINT
替换为你的GraphQL服务器的实际端点。
watchQuery
或query
方法来执行GraphQL查询:import { Component, OnInit } from '@angular/core';
import { GraphqlService } from 'path/to/graphql.service';
import { ApolloQueryResult } from '@apollo/client/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
constructor(private graphqlService: GraphqlService) {}
ngOnInit(): void {
this.graphqlService.apolloClient
.watchQuery({
query: YOUR_GRAPHQL_QUERY
})
.valueChanges.subscribe((result: ApolloQueryResult<any>) => {
// 处理查询结果
});
}
}
请将YOUR_GRAPHQL_QUERY
替换为你的实际GraphQL查询。
这样,当GraphQL查询发生错误时,错误信息将被打印到控制台,并且你可以根据需要进行进一步处理。
对于Angular for GraphQL中使用Apollo客户端处理错误的完善和全面的答案,暂时没有特定的腾讯云相关产品和产品介绍链接地址。
领取专属 10元无门槛券
手把手带您无忧上云