如何在 Angular 4+ 中使用 Apollo 客户端 GraphQL

Apollo Client是针对 Angular、JavaScript 和原生平台的灵活、社区驱动的 GraphQL 客户端,旨在从头开始轻松构建使用 GraphQL 获取数据的 UI 组件,这篇文章简要概述了如何使用 Apollo 客户端 GraphQL 与您的 Angular 4+. 因此,您需要在阅读以下帖子之前了解 GraphQl 和 Angular 4+。

设置:

安裝 Angular CLI 以執行下列命令開始之前:

1ng add apollo-angular

您需要设置的一件事是您的 GraphQL 服务器的 URL,所以打开src/app/graphql.module.ts并设置 URI 变量:

1const uri = 'https://w5xlvm3vzz.lp.gql.zone/graphql'; //our test Graphql Server which returns rates

想要的:

我们将使用 Apollo 将 GraphQL 查询结果附加到我们的 Angular UI 元素中,我们将使用 'Apollo.watchQuery' 方法. 我们需要通过 'graphql-tag' 库将我们的查询解析到 GraphQL 文档中。 'Apollo.watchQuery' 方法预计一个参数,一个具有选项的对象,你可以在同一个对象中提供任何可用的选项。

 1const currentUser = gql`query currentUser($avatarSize: Int!) {
 2    currentUser {
 3      login
 4      avatar_url(avatarSize: $avatarSize)
 5    }
 6  }`;
 7
 8@Component({template:`Login: {{currentUser?.profile}}`,})
 9class UserComponent implements OnInit, OnDestroy {
10  currentUser: any;
11  private querySubscription: Subscription;
12  ngOnInit() {
13    this.querySubscription = this.apollo.watchQuery({
14      query: currentUser,
15      variables: {
16        avatarSize: 100,
17      },
18    }).valueChanges.subscribe(({data}) => {
19      this.currentUser = data.currentUser;
20    });
21  }
22  ngOnDestroy() {
23    this.querySubscription.unsubscribe();
24  }
25}

突变:

Apollo 处理 GraphQL 突变. 突变与语法中的查询相同,唯一的区别是您使用的关键字突变而不是查询。

GraphQL 突变由两个部分组成:

  1. 具有参数的突变名称,代表在服务器上执行的实际操作
  2. 您想要从突变结果返回的字段更新客户端

我们将使用突变方法,我们可以通过选项来突变,当我们称呼它时:

 1const submitRepository = gql`mutation submitRepository($repoFullName: String!) {
 2    submitRepository(repoFullName: $repoFullName) {
 3      createdAt
 4    }
 5  }`;
 6
 7@Component({ ... })
 8class NewEntryComponent {
 9  constructor(private apollo: Apollo) {}
10
11  newRepository() {
12    this.apollo.mutate({
13      mutation: submitRepository,
14      variables: {
15        repoFullName: 'graphql/angular'
16      }
17    }).subscribe(({ data }) => {
18      console.log('got data', data);
19    },(error) => {
20      console.log('there was an error sending the query', error);
21    });
22  }
23}

乐观的回应:

例如,当用户对一篇文章发表评论时,我们希望在背景下立即显示新评论,而不需要等待到到服务器的圆形旅行的延迟,这就是我们称之为 Optimistic UI

Apollo 客户端为您提供了指定optimisticResponse选项的方法,该选项将用于立即更新活跃的查询,就像服务器的突变响应一样。

 1import { Component } from '@angular/core';
 2import { Apollo } from 'apollo-angular';
 3import gql from 'graphql-tag';
 4
 5const submitComment = gql`mutation submitComment($repoFullName: String!, $commentContent: String!) {
 6    submitComment(repoFullName: $repoFullName, commentContent: $commentContent) {
 7      postedBy {
 8        login
 9        html_url
10      }
11      createdAt
12      content
13    }
14  }`;
15
16@Component({ ... })
17class CommentPageComponent {
18  currentUser: User;
19
20  constructor(private apollo: Apollo) {}
21
22  submit({ repoFullName, commentContent }) {
23    this.apollo.mutate({
24      mutation: submitComment,
25      variables: { repoFullName, commentContent },
26      optimisticResponse: {
27        __typename: 'Mutation',
28        submitComment: {
29          __typename: 'Comment',
30          postedBy: this.currentUser,
31          createdAt: +new Date,
32          content: commentContent,
33        },
34      },
35    }).subscribe();
36  }
37}

结论

在本文中,我们对使用 Apollo 客户端 GraphQL 与 Angular 进行了快速研究。

Published At
Categories with 技术
Tagged with
comments powered by Disqus