最近很多小伙伴都在问使用ApolloClient动态设置React组件的GraphQL查询这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展angular–如何使用graphql变异
最近很多小伙伴都在问使用Apollo Client动态设置React组件的GraphQL查询这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展angular – 如何使用graphql变异自动刷新Apollo Client正在监视的查询?、Apollo Client 1.0 发布,JavaScript 的 GraphQL 客户端、Apollo Client Angular:如何将从查询中获得的数据作为参数传递给 graphql 中的另一个查询?、Apollo Client —— JavaScript GraphQL 客户端等相关知识,下面开始了哦!
本文目录一览:- 使用Apollo Client动态设置React组件的GraphQL查询
- angular – 如何使用graphql变异自动刷新Apollo Client正在监视的查询?
- Apollo Client 1.0 发布,JavaScript 的 GraphQL 客户端
- Apollo Client Angular:如何将从查询中获得的数据作为参数传递给 graphql 中的另一个查询?
- Apollo Client —— JavaScript GraphQL 客户端
使用Apollo Client动态设置React组件的GraphQL查询
我正在构建一个React前端,允许用户从静态查询列表中选择一个“活动”查询,并将其展平到要显示在表中的结果。将GraphQL查询从高阶组件传递到嵌套子组件的最佳方法是什么?
我见过的大多数文档/解决方案都集中于将具有动态条件的静态查询从组件状态绑定到组件,这对于我的目的不起作用,因为不同的静态查询具有不同的字段和查询不同的节点类型。
什么是最佳实践/推荐方法?我觉得这不是一个非常独特的用例,但是我似乎找不到任何可以做类似事情的示例。
我将Apollo-Client / Redux用作客户端存储。
下面是该组件的粗略概述:
class GridViewPage extends React.Component{ constructor(props, context) { super(props, context); this.state = { activeQuery = ... Stores the selected query ... }; } render() { return ( <div className="gridContainer"> ...Component here allows users to select a query from the active list and saves it/it''s ID/Index to the state... <Panel collapsible> ...Some toolbar components... </Panel> ...Component here displays the result of the query (Ideally by receiving the query or the result of as a prop?)... </div> ); }}GridViewPage.propTypes = { grids: PropTypes.array.isRequired, actions: PropTypes.object.isRequired};function mapStateToProps(state, ownProps) { return { // Receives list of available queries as a prop grids: state.grids };}
答案1
小编典典让我们以以下组件为例:
ProfileWithData.js
import React, { Component, PropTypes } from ''react'';import { graphql } from ''react-apollo'';import gql from ''graphql-tag'';class Profile extends Component { ... }Profile.propTypes = { data: PropTypes.shape({ loading: PropTypes.bool.isRequired, currentUser: PropTypes.object, }).isRequired,};// We use the gql tag to parse our query string into a query documentconst CurrentUserForLayout = gql` query CurrentUserForLayout { currentUser { login avatar_url } }`;const ProfileWithData = graphql(CurrentUserForLayout)(Profile);
用更高阶的组件将其包装起来非常容易:
Profile.js
import React, { Component, PropTypes } from ''react'';export class Profile extends Component { ... }Profile.propTypes = { data: PropTypes.shape({ loading: PropTypes.bool.isRequired, currentUser: PropTypes.object, }).isRequired,};
createProfileWithData.js
import React, { Component, PropTypes } from ''react'';import { graphql } from ''react-apollo'';import { Profile } from ''./Profile''export default function createProfileWithData(query) => { return graphql(query)(Profile);}
然后,您可以像这样使用它:
Page.js
import React, { Component, PropTypes } from ''react'';import gql from ''graphql-tag'';import createProfileWithData from ''./createProfileWithData'';class Page extends Component { renderProfileWithData() { const { textQuery } = this.props; // Simplest way, though you can call gql as a function too const graphQLQuery = gql`${textQuery}`; const profileWithDataType = createProfileWithData(graphQLQuery); return ( <profileWithDataType /> ); } render() { return (<div> .. {this.renderProfileWithData()} .. </div>) }}Profile.propTypes = { textQuery: PropTypes.string.isRequired,};
我认为你说对了。
当然,不会收到您的个人资料props.data.currentUser
,而是props.data.*
取决于根查询,并且您将根据内容进行适当的处理。
注意 :这是直接在Stack Overflow中编写的,因此,如果您遇到任何问题-lmk,我会修复它。
angular – 如何使用graphql变异自动刷新Apollo Client正在监视的查询?
我在graphQL之上构建了一个Web服务,它运行得很好.我面临的唯一问题是项目的客户端.例如(请参阅下面的代码),在运行createVideo()后,我的组件的数据属性是一个可观察的,它正在观察查询不会自动刷新并且在回调上手动调用apollo.query似乎不需要任何影响,因为查询返回缓存的结果,而不是服务器的结果.
我错过了什么吗?
app.component.ts import {Component,OnInit} from '@angular/core'; import {Apollo,ApolloQueryObservable} from 'apollo-angular'; import 'rxjs/Rx'; import gql from 'graphql-tag'; // http://dev.apollodata.com/angular2/mutations.html const NewVideoQuery = gql` mutation AddVideoQuery($title: String!,$duration: Int!,$watched: Boolean!){ createVideo(video: { title: $title,duration: $duration,watched: $watched } ){ id,title } } `; const VideoQuery = gql` { videos { id,title } } `; @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { data: ApolloQueryObservable<any>; video: any = {}; constructor(private apollo: Apollo) { } ngOnInit() { this.data = this.apollo.watchQuery({query: VideoQuery}); } createVideo() { /** * This will send a mutate query to the server. */ // @todo After running the mutate,the watch query doesn't refresh this.apollo.mutate({ mutation: NewVideoQuery,variables: { 'title': this.video.title || 'Some Video' + Math.floor(Math.random() * 10),'duration': 123213,'watched': true } }).subscribe((afterMutation) => { console.log(afterMutation); // This fires but query doesn't hit the server since it's coming from cache. // @todo Not even by re-running it here this.apollo.query({query: VideoQuery}) .subscribe((data) => { console.log(data); }); },(err) => alert(err)); } }
//app.component.html <div *ngFor="let x of data | async | select: 'videos'"> <div><b>{{x.id}}</b>{{x.title}}</div> </div> <label> Title <input type="text" [(ngModel)]="video.title"> </label> <button (click)="createVideo()">{{title}}</button>
解决方法
Apollo-client默认缓存我们的查询并重新运行相同的查询当然会从缓存中返回结果,而不是从服务器返回.
当然,因为我做了一个突变来创建一个新记录,我希望服务器自动刷新数据集,但事实并非如此.
为了解决这个问题,我提出了从createVideo变异的成功回调中重新运行查询的想法,但这次我添加了一个名为fetchPolicy的特殊选项,它支持以下值:
'cache-first' | 'cache-and-network' | 'network-only' | 'cache-only' | 'standby'
最后我的fetch查询如下所示:
this.apollo.query({query: VideoQuery,fetchPolicy: 'network-only'}) .subscribe(()=>{ console.log('refresh done,our watchQuery will update') })
奖金提示:
关于Apollo的另一个有趣的功能是你可以设置一个像这样的池间隔,这样你的数据总是与服务器同步
this.data = this.apollo.watchQuery({query: VideoQuery,pollInterval: 10000});
Apollo Client 1.0 发布,JavaScript 的 GraphQL 客户端
Apollo Client 1.0 发布了,Apollo Client 是一个全功能的 GraphQL 客户端,用于 React 、Angular 的交互。允许你轻松通过 GraphQL 获取数据并构建 UI 组件。
Apollo Client 1.0 的改进记录包括:
It works with any GraphQL server and schema.
It’s easy to get started with, and extensively documented.
It works seamlessly with your favorite React community tools like Redux and Recompose.
It has integrations for Angular, Ember, Vue, Meteor, Next.js, and more.
It has built-in tools for optimistic UI, SSR, pagination, loading state, and everything else you need to build an app.
It supports GraphQL subscriptions out of the box.
It gives you full control over your GraphQL store.
It has its own Apollo Developer Tools to help you understand your app.
详细介绍请看官方发行说明。
Apollo Client Angular:如何将从查询中获得的数据作为参数传递给 graphql 中的另一个查询?
如何解决Apollo Client Angular:如何将从查询中获得的数据作为参数传递给 graphql 中的另一个查询??
我正在使用 apollo clinet angular 从使用 graphql 的第三方获取数据。我想使用从 graphql 查询中获得的一些数据,以便在另一个 graphql 查询中使用。例如
const customer = gql`query customer{
customer {
id
}
....
....
this.apollo.watchQuery({
query: customer
}).valueChanges.subscribe((customer: any) => {
this.customerId = customer.data?.customer.id;
});
我想在另一个查询中使用 this.customerId
作为参数,如下所示:
const customerinformation = gql`
query customerinformation($customer: Long!){
customerinformation{
first_name
last_name
address
}
}`;
....
....
if(this.customerId){
this.apollo.watchQuery({
query: customerinformation,variables: {
customer: this.customerId
},})
.valueChanges.subscribe((result: any) => {
console.log(result);
});
}
但我没有从第二个查询中获取数据,因为未执行代码块,因为 this.customerId
未定义(在我调试代码时发现)。有人可以在这里帮助我吗?。
解决方法
变量 this.customerId
是异步初始化的。第二个调用必须与第一个调用耦合。这取决于您希望如何执行它们。一种最快的方法是使用高阶映射运算符(如 switchMap
)从一个 observable 映射到另一个 observable。
import { NEVER } from ''rxjs'';
import { switchMap } from ''rxjs/operators'';
const customer = gql`query ...`;
this.apollo.watchQuery({ query: customer }).valueChanges.pipe(
switchMap((customer: any) => { // <-- map to other observable
this.customerId = customer;
const customerInformation = gql` query ...`;
if (!!customer) {
return this.apollo.watchQuery({
query: customerInformation,variables: {
customer: this.customerId
},}).valueChanges;
}
return NEVER; // <-- do NOT emit if `customer` is undefined
).subscribe(
(value: any) => { console.log(result); },(error: any) => { console.log(error); }
);
Apollo Client —— JavaScript GraphQL 客户端
Apollo Client 是一个全功能的 GraphQL 客户端,用于 React 、Angular 的交互。允许你轻松通过 GraphQL 获取数据并构建 UI 组件。
今天的关于使用Apollo Client动态设置React组件的GraphQL查询的分享已经结束,谢谢您的关注,如果想了解更多关于angular – 如何使用graphql变异自动刷新Apollo Client正在监视的查询?、Apollo Client 1.0 发布,JavaScript 的 GraphQL 客户端、Apollo Client Angular:如何将从查询中获得的数据作为参数传递给 graphql 中的另一个查询?、Apollo Client —— JavaScript GraphQL 客户端的相关知识,请在本站进行查询。
本文标签: