博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
angular4前后端分离_如何在Angular 4+中使用Apollo客户端GraphQL
阅读量:2506 次
发布时间:2019-05-11

本文共 5218 字,大约阅读时间需要 17 分钟。

angular4前后端分离

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.

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

建立: (Setup:)

Install before you start by running the following command:

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

  • 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 .

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

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结合使用。

翻译自:

angular4前后端分离

转载地址:http://nlhgb.baihongyu.com/

你可能感兴趣的文章
Tecplot: Legend和图像中 Dashed/Dash dot/Long dash 等虚线显示没有区别的问题
查看>>
win8 开发之旅(2) --连连看游戏开发 项目错误的总结
查看>>
视频转换工具ffmpeg
查看>>
一、 object c -基础学习第一天 如何定义一个类
查看>>
C#调用C++编译的DLL详解
查看>>
Kali Linux的安装
查看>>
我的大学生活-5-08-赵心宁
查看>>
bzoj1708[Usaco2007 Oct]Money奶牛的硬币(背包方案数dp)
查看>>
P2700逐个击破(并查集/树形dp)
查看>>
python几大排序算法
查看>>
hdu 4619 二分图最大匹配 ——最大独立集
查看>>
VM CentOS 问题汇总
查看>>
这段时间的小结
查看>>
ANDROID_MARS学习笔记_S01原始版_021_MP3PLAYER001_下载mp3文件
查看>>
SQLServer视图
查看>>
入门阶段
查看>>
Android中使用http协议访问网络
查看>>
vs win32 & MFC 指针默认位置
查看>>
Join 与 CountDownLatch 之间的区别
查看>>
js存cookie
查看>>