How to Setup Apollo Graphql Client with Angular

How to Setup Apollo Graphql Client with Angular

GraphQL is both an API query language and a runtime for executing those queries using your current data. GraphQL allows clients the power to ask for precisely what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools by providing a clear and intelligible description of the data in your API.

Data management in current apps is difficult. The majority of applications demand:

  • Diverse front-end clients for various platforms (web, iOS, etc.) with varying data specifications

  • A backend that provides data from many sources to clients (MySQL, Redis, etc.)

  • For both the client and the backend, complex state and cache management is required.

You may significantly lessen these difficulties by implementing GraphQL.

So in this tutorial, you will set up GraphQL in an Angular app using the powerful tool Apollo.

Outline

  • Install Prerequisites for Angular

  • Install Prerequisites for GraphQL

  • Setup and Query

Install Prerequisites for Angular

You'll need the following to install Angular on your local system:

  • Node.js

An active LTS or maintenance LTS version of Node.js is required for Angular. It can be downloaded from here

Run node -v in a terminal window to see what version of Node.js is installed on your machine.

  • Node package manager (npm)

For many features and functions, Angular, Angular CLI, and Angular applications rely on npm packages. npm is required to download and install npm packages. npm comes pre-installed with Node.js. Run npm -v in a terminal window to see if you have the npm client installed.

  • Install the Angular CLI

Open a terminal window and type the following command to install the Angular CLI: npm install -g @angular/cli

Now run ng new angular-graphql to create your angular app

Go to the workspace folder, for example, angular-graphql. Execute the command below:

cd angular-graphql
ng serve --open

If all goes well your app should open up in the browser on port 4200 or your selected port as shown below

angular app launch

Install Prerequisites for GraphQL

First, let's install some packages to get Apollo up and running:

npm install apollo-angular @apollo/client graphql

**Note: ** The apollo/client package requires AsyncIterable so make sure your tsconfig.json includes esnext.asynciterable:

{
  "compilerOptions": {
    // ...
    "lib": [
      "es2017",
      "dom",
      "esnext.asynciterable"
    ]
  }
}

You have succeeded in installing all necessary dependencies necessary to work with GraphQL in Angular

Setup and Query

Now proceed to app.module.ts file to configure Apollo:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import {HttpClientModule} from '@angular/common/http';
import {APOLLO_OPTIONS} from 'apollo-angular';
import {HttpLink} from 'apollo-angular/http';
import {InMemoryCache} from '@apollo/client/core';

@NgModule({
 declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, 
    HttpClientModule,
    AppRoutingModule
],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: (httpLink: HttpLink) => {
        return {
          cache: new InMemoryCache(),
          link: httpLink.create({
            uri: 'https://48p1r2roz4.sse.codesandbox.io',
          }),
        };
      },
      deps: [HttpLink],
    },
  ],
bootstrap: [AppComponent]
})
export class AppModule {}

Proceed to app.component.ts to make your request to the GraphQL server

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

const GET_RATES = gql`
{
  rates(currency: "USD") {
    currency
    rate
  }
}
`;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  rates: any[];
  loading = true;
  error: any;

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.apollo
      .watchQuery<any>({
        query: GET_RATES,
      })
      .valueChanges.subscribe((result: any) => {
        this.rates = result?.data?.rates;
        this.loading = result.loading;
        this.error = result.error;
      });
  }
}

Now display the data in the template app.compontent.html

<div *ngIf="loading">
  Loading...
</div>
<div *ngIf="error">
  Error :(
</div>
<div *ngIf="rates">
  <div *ngFor="let rate of rates">
    <p>{{ rate.currency }}: {{ rate.rate }}</p>
  </div>
</div>

<router-outlet></router-outlet>

You should see the data displayed in the browser

Displayed results

Summary

Setting up Angular to work with GraphQL has been made so easy with the help of Apollo.

I hope you enjoyed the article, feel free to share.