1

我有一个从 GraphQL 服务器访问数据的 Angular 7 应用程序。

我直接实现了文档中的示例: https ://www.apollographql.com/docs/react/advanced/caching.html#automatic-updates

这是获取 post 对象并执行 upvote 突变的服务。

export class PostService {

  constructor(private apollo: Apollo) { }

  public getPost() {
    return this.apollo.query({
      query: gql`query getPost($id: String!) {
        post(id: $id) {
          id
          score
        }
      }`,
      variables: { id: '123' }
    });
  }

  public upvote() {
    return this.apollo.mutate({
      mutation: gql`mutation upvote($id: String!) {
        upvotePost(id: $id) {
          id
          score
        }
      }`,
      variables: { id: '123' }
    });
  }
}

在我的 component.ts 文件中

  public post = this.postService.getPost();
  public vote() {
    this.postService.upvote().subscribe(console.log);
  }

在我的 component.html 中

    <input type="text" [value]="(post | async).data.post.score" />
    <button class="button" (click)="vote()"></button>

框中的值不会改变。

如果我添加一个调用此函数的附加按钮

public updateView() {
  post = this.postService.getPost();
}

gui 将在不查询服务器的情况下更新,因此显然来自缓存。

根据规范,这个手动刷新步骤不应该是必要的。

If the id field on both results matches up, then the score field everywhere in our UI will be updated automatically!

我的包的版本:

  • 阿波罗角:1.5.0
  • 阿波罗角链接-http:1.4.0
  • 阿波罗-角-链接-http-common:1.4.0
  • 阿波罗缓存:1.1.25
  • 阿波罗缓存内存:1.4.2
  • 阿波罗客户端:2.4.12

我需要更改什么,以便在原始请求返回的 observable 中实际更新结果?

还是我只是不了解预期的机制?

4

2 回答 2

2

现在我使用了文档的角度部分而不是 React 部分,我找到了解决方案。(@tombraider 感谢您将我推向正确的方向。)

而不是query,我需要使用watchQuery.

  public getPost(id: string) {
    return this.apollo.watchQuery({
      query: gql`query getPost($id: String!) {
        post(id: $id) {
          id
          score
        }
      }`,
      variables: { id }
    }).valueChanges;
  }

服务功能的此更改版本不断更新 GUI。

于 2019-02-11T16:38:55.040 回答
1

这里有点疯狂的猜测,但我建议这是因为您没有编写内联查询;文档会有所不同。看看refetchQueries你可以传递给你的 Mutation 的道具,即

  public upvote() {
    return this.apollo.mutate({
      mutation: gql`mutation upvote($id: String!) {
        upvotePost(id: $id) {
          id
          score
        }
      }`,
      variables: { id: '123' },
      refetchQueries: [],
    });

当你的突变执行时,你告诉 GraphQL 你想要执行你在该refetchQueries数组中提供的查询。因此,缓存将更新。但是,我不是 100% 相信您的查询会执行,因为您在技术上没有订阅它,您所做的只是执行一次性承诺以从 GraphQL 端点获取数据。

于 2019-02-11T16:03:00.607 回答