angular4前后端分离_如何在Angular 4+中使用Apollo客户端GraphQL

盖夕
2023-12-01

angular4前后端分离

Apollo Client is the flexible, community-driven GraphQL client for Angular, JavaScript, and native platforms. It is designed from the ground up to make it easy to build UI components that fetch data with GraphQL. This article is a quick summary about how to use Apollo client GraphQL with your Angular 4+. Therefore you need to know about GraphQl and Angular 4+ before you read the following post.

Apollo Client是用于Angular,JavaScript和本机平台的灵活的,社区驱动的GraphQL客户端。 它是从头开始设计的,可轻松构建使用GraphQL提取数据的UI组件。 本文是有关如何在Angular 4+中使用Apollo客户端GraphQL的快速摘要。 因此,在阅读以下文章之前,您需要了解GraphQl和Angular 4+。

建立: (Setup:)

Install Angular CLI before you start by running the following command:

在开始之前,通过运行以下命令安装Angular CLI

  • ng add apollo-angular

    ng添加阿波罗角

One thing you need to set is the URL of your GraphQL Server, so open src/app/graphql.module.ts and set URI variables:

您需要设置的一件事是GraphQL Server的URL,因此打开src/app/graphql.module.ts并设置URI变量:

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

查询: (Queries:)

We will use Apollo to attach GraphQL query results to our Angular UI elements, we will use Apollo.watchQuery method. We need to parse our query into a GraphQL document using the graphql-tag library. Apollo.watchQuery method expects one argument, an object with options, you can provide any available option in the same object. If your query takes variables, this is the place to pass them in:

我们将使用Apollo将GraphQL查询结果附加到我们的Angular UI元素,我们将使用Apollo.watchQuery方法。 我们需要使用graphql-tag库将查询解析为GraphQL文档。 Apollo.watchQuery方法需要一个参数,一个带有选项的对象,您可以在同一对象中提供任何可用的选项。 如果您的查询使用变量,则可以在其中传递变量:

const currentUser = gql`query currentUser($avatarSize: Int!) {
    currentUser {
      login
      avatar_url(avatarSize: $avatarSize)
    }
  }`;

@Component({template:`Login: {{currentUser?.profile}}`,})
class UserComponent implements OnInit, OnDestroy {
  currentUser: any;
  private querySubscription: Subscription;
  ngOnInit() {
    this.querySubscription = this.apollo.watchQuery({
      query: currentUser,
      variables: {
        avatarSize: 100,
      },
    }).valueChanges.subscribe(({data}) => {
      this.currentUser = data.currentUser;
    });
  }
  ngOnDestroy() {
    this.querySubscription.unsubscribe();
  }
}

变异: (Mutations:)

Apollo handles GraphQL mutations. Mutations are identical to queries in syntax, the only difference being that you use the keyword mutation instead of query.

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

GraphQL mutations consist of two parts:

GraphQL突变包括两个部分:

  1. The mutation name with arguments, which represents the actual operation to be done on the server.

    带有参数的突变名称,它表示要在服务器上执行的实际操作。
  2. The fields you want back from the result of the mutation to update the client.

    您想要从变异结果中返回的字段以更新客户端。

We will use the mutate method. We can pass options to mutate when we call it:

我们将使用mutate方法。 我们可以在调用它时传递选项来进行变异:

const submitRepository = gql`mutation submitRepository($repoFullName: String!) {
    submitRepository(repoFullName: $repoFullName) {
      createdAt
    }
  }`;

@Component({ ... })
class NewEntryComponent {
  constructor(private apollo: Apollo) {}

  newRepository() {
    this.apollo.mutate({
      mutation: submitRepository,
      variables: {
        repoFullName: 'graphql/angular'
      }
    }).subscribe(({ data }) => {
      console.log('got data', data);
    },(error) => {
      console.log('there was an error sending the query', error);
    });
  }
}

乐观的回应: (Optimistic Response:)

Sometimes before the server responds with the result, we can predict the result of the mutation. For example, when a user comments on an article, we want to show the new comment in context immediately, without waiting on the latency of a round trip to the server, This is what we call Optimistic UI.

有时,在服务器响应结果之前,我们可以预测突变的结果。 例如,当用户评论文章时,我们希望立即在上下文中显示新评论,而不必等待往返服务器的延迟,这就是我们所谓的Optimistic UI

Apollo Client gives you a way to specify the optimisticResponse option, that will be used to update active queries immediately, in the same way that the server’s mutation response will. Once the actual mutation response returns, the optimistic part will be thrown away and replaced with the real result.

Apollo Client为您提供了一种指定optimisticResponse选项的方法,该选项将用于立即更新活动查询,就像服务器的变异响应一样。 一旦实际的突变响应返回,乐观部分将被丢弃,并替换为实际结果。

import { Component } from '@angular/core';
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';

const submitComment = gql`mutation submitComment($repoFullName: String!, $commentContent: String!) {
    submitComment(repoFullName: $repoFullName, commentContent: $commentContent) {
      postedBy {
        login
        html_url
      }
      createdAt
      content
    }
  }`;

@Component({ ... })
class CommentPageComponent {
  currentUser: User;

  constructor(private apollo: Apollo) {}

  submit({ repoFullName, commentContent }) {
    this.apollo.mutate({
      mutation: submitComment,
      variables: { repoFullName, commentContent },
      optimisticResponse: {
        __typename: 'Mutation',
        submitComment: {
          __typename: 'Comment',
          postedBy: this.currentUser,
          createdAt: +new Date,
          content: commentContent,
        },
      },
    }).subscribe();
  }
}

结论 (Conclusion)

In this article, we took a quick look at using Apollo Client GraphQL with Angular.

在本文中,我们快速了解了如何将Apollo Client GraphQL与Angular结合使用。

翻译自: https://www.digitalocean.com/community/tutorials/using-apollo-client-graphql-with-angular-4

angular4前后端分离

 类似资料: