在Apollo Angular客户端中使用缓存的方法如下:
npm install apollo-angular apollo-angular-link-http apollo-cache-inmemory graphql
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
@NgModule
装饰器中,将Apollo和HttpLink添加到imports
数组中:@NgModule({
imports: [
ApolloModule,
HttpLinkModule
],
// ...
})
export class AppModule {
constructor(
apollo: Apollo,
httpLink: HttpLink
) {
// ...
}
}
export class AppModule {
constructor(
apollo: Apollo,
httpLink: HttpLink
) {
const cache = new InMemoryCache();
apollo.create({
link: httpLink.create({ uri: 'http://localhost:3000/graphql' }),
cache: cache
});
}
}
import { Apollo } from 'apollo-angular';
import { gql } from 'apollo-boost';
export class MyComponent {
constructor(private apollo: Apollo) { }
}
export class MyComponent {
constructor(private apollo: Apollo) { }
ngOnInit() {
this.apollo.query({
query: gql`
query {
todos {
id
title
}
}
`
}).subscribe(result => {
console.log(result.data);
});
}
}
在上面的示例中,我们使用apollo.query
方法发送了一个GraphQL查询,并通过result.data
获取了返回的数据。如果之前已经发送过相同的查询,Apollo会尝试从缓存中获取数据,而不是发出网络请求。
这就是在Apollo Angular客户端中使用缓存的基本方法。根据具体需求,可能还需要配置其他高级缓存选项,例如缓存的过期时间、缓存的键等。