DEV Community

Cover image for All you need to know about Apollo-Angular Queries
Daniel Osunkwo
Daniel Osunkwo

Posted on • Updated on

All you need to know about Apollo-Angular Queries

Simplifying Data Fetching in Angular Applications

Introduction:
With Apollo Angular, you can build UI components that fetch data with GraphQL. It is a flexible, community-driven GraphQL client for Angular. You can get the most value out of Apollo Client by integrating it with one of its view layer integrations.
It is designed from the ground up to make it easy to build UI components that fetch data with GraphQL.

The Angular Toolbox
Apollo is designed to work with all this tools:
Angular Schematics: Apollo Angular supports

ng-add
Enter fullscreen mode Exit fullscreen mode

and

ng-update
Enter fullscreen mode Exit fullscreen mode

NativeScript: Apollo works well out of the box in NativeScript.
Angular Router:
Ionic

Installation:-

  1. The best way to get Apollo Angular is by running this command on your terminal.
ng add apollo-angular 
Enter fullscreen mode Exit fullscreen mode
  1. Another thing is to set the URL of your GraphQL Server, open src/app/graphql.module.ts and set uri variables-

src/app/graphql.module.ts

const uri = 'https://48p1r2roz4.sse.codesandbox.io';
Enter fullscreen mode Exit fullscreen mode

You can also install without using Angular Schematics by using this commands on your terminal

npm i apollo-angular @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode

Queries
Query simply means retrieving data and or Information from the database
In Apollo Angular we simply need to parse our query into a GraphQL document using the gql tag from apollo-angular library using the Apollo.watchQuery method

Example:

import { Apollo, gql } from 'apollo-angular';
import { Subscription } from 'rxjs';
import { Component, OnDestroy, OnInit } from '@angular/core';

// We use the gql tag to parse our query string into a query document
const GET_POSTS = gql`
  query GetPosts {
    posts {
      id
      title
    }
  }
`;

@Component({
  // ...
})
class PostsComponent implements OnInit, OnDestroy {
  loading: boolean;
  posts: any;

  private querySubscription: Subscription;

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.querySubscription = this.apollo
      .watchQuery<any>({
        query: GET_POSTS,
      })
      .valueChanges.subscribe(({ data, loading }) => {
        this.loading = loading;
        this.posts = data.posts;
      });
  }

  ngOnDestroy() {
    this.querySubscription.unsubscribe();
  }
}
Enter fullscreen mode Exit fullscreen mode

As a result of the watchQuery method, we get a QueryRef object with a valueChanges property.

Top comments (0)