要在Angular中使用GraphQL客户端Apollo,您需要按照以下步骤进行配置:
npm install @apollo/client graphql
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular/http';
import { InMemoryCache } from '@apollo/client/core';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
ApolloModule,
HttpLinkModule
],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: (httpLink: HttpLink) => {
return {
cache: new InMemoryCache(),
link: httpLink.create({ uri: 'https://your-graphql-endpoint' })
};
},
deps: [HttpLink]
}
]
})
export class AppModule {}
import { Component } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';
@Component({
selector: 'app-root',
template: `
<div *ngIf="loading">Loading...</div>
<div *ngIf="error">Error: {{ error.message }}</div>
<div *ngIf="data">{{ data }}</div>
`
})
export class AppComponent {
loading = true;
error: any;
data: any;
constructor(private apollo: Apollo) {
this.apollo.query({
query: gql`
query {
hello
}
`
}).subscribe(({ data, loading, error }) => {
this.loading = loading;
this.error = error;
this.data = data;
});
}
}
以上是使用Angular中Apollo客户端的基本配置和用法。您可以根据您的需求进一步定制和调整配置。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。