Angular4+でApolloクライアントGraphQLを使用する方法
Apollo Client は、Angular、JavaScript、およびネイティブプラットフォーム向けの柔軟なコミュニティ主導のGraphQLクライアントです。 これは、GraphQLを使用してデータをフェッチするUIコンポーネントを簡単に構築できるようにゼロから設計されています。 この記事は、Angular4+でApolloクライアントGraphQLを使用する方法についての簡単な要約です。 したがって、次の投稿を読む前に、GraphQlとAngular4+について知っておく必要があります。
設定:
次のコマンドを実行して開始する前に、AngleCLIをインストールします。
- ng add apollo-angular
設定する必要があるのはGraphQLサーバーのURLなので、開いてください src/app/graphql.module.ts
URI変数を設定します。
const uri = 'https://w5xlvm3vzz.lp.gql.zone/graphql'; //our test Graphql Server which returns rates
クエリ:
Apolloを使用してGraphQLクエリ結果をAngularUI要素にアタッチします。 Apollo.watchQuery
方法。 を使用してクエリをGraphQLドキュメントに解析する必要があります graphql-tag
図書館。 Apollo.watchQuery
メソッドは1つの引数、オプション付きのオブジェクトを想定しています。同じオブジェクトで使用可能なオプションを指定できます。 クエリが変数を受け取る場合、これはそれらを渡す場所です:
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();
}
}
突然変異:
ApolloはGraphQLミューテーションを処理します。 ミューテーションは構文のクエリと同じですが、唯一の違いは、クエリの代わりにキーワードミューテーションを使用することです。
GraphQLミューテーションは、次の2つの部分で構成されます。
- サーバーで実行される実際の操作を表す、引数付きのミューテーション名。
- クライアントを更新するためにミューテーションの結果から戻したいフィールド。
を使用します 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);
});
}
}
楽観的な反応:
サーバーが結果で応答する前に、ミューテーションの結果を予測できる場合があります。 たとえば、ユーザーが記事にコメントした場合、サーバーへのラウンドトリップの待ち時間を待たずに、コンテキスト内で新しいコメントをすぐに表示したいと考えています。これを OptimisticUIと呼びます。
Apolloクライアントはあなたに指定する方法を提供します 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();
}
}
結論
この記事では、AngularでApolloClientGraphQLを使用する方法について簡単に説明しました。