Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

GraphQL with Angular

GraphQL is a query language for your API and a runtime for executing those queries. Integrating GraphQL with Angular allows you to efficiently fetch and manage data in your Angular applications. This guide covers the basics of setting up and using GraphQL with Angular.

Setting Up Apollo Client

Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. To set up Apollo Client in your Angular project, follow these steps:

ng add apollo-angular

Configuring Apollo Client

Configure Apollo Client in your Angular project:

// src/app/graphql.module.ts
import { NgModule } from '@angular/core';
import { APOLLO_OPTIONS, ApolloModule } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { InMemoryCache } from '@apollo/client/core';

@NgModule({
  exports: [ApolloModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: (httpLink: HttpLink) => {
        return {
          cache: new InMemoryCache(),
          link: httpLink.create({ uri: 'https://your-graphql-endpoint.com/graphql' }),
        };
      },
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

Using Apollo Client

Use Apollo Client to execute GraphQL queries and mutations in your Angular components:

// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';

const GET_DATA = gql\`
  query GetData {
    data {
      id
      name
    }
  }
\`;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  data: any[] = [];

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.apollo.watchQuery({
      query: GET_DATA,
    }).valueChanges.subscribe(({ data }) => {
      this.data = data.data;
    });
  }
}

Executing Mutations

Execute GraphQL mutations to modify data on the server:

// src/app/app.component.ts
const ADD_ITEM = gql\`
  mutation AddItem($name: String!) {
    addItem(name: $name) {
      id
      name
    }
  }
\`;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  data: any[] = [];
  itemName: string = '';

  constructor(private apollo: Apollo) {}

  addItem() {
    this.apollo.mutate({
      mutation: ADD_ITEM,
      variables: {
        name: this.itemName,
      },
    }).subscribe(({ data }) => {
      this.data.push(data.addItem);
      this.itemName = '';
    });
  }
}

Handling Subscriptions

Handle GraphQL subscriptions to receive real-time updates:

// src/app/graphql.module.ts
import { WebSocketLink } from '@apollo/client/link/ws';

@NgModule({
  exports: [ApolloModule],
  providers: [
    {
      provide: APOLLO_OPTIONS,
      useFactory: (httpLink: HttpLink) => {
        return {
          cache: new InMemoryCache(),
          link: httpLink.create({
            uri: 'https://your-graphql-endpoint.com/graphql',
          }),
        };
      },
      deps: [HttpLink],
    },
  ],
})
export class GraphQLModule {}

const WS_LINK = new WebSocketLink({
  uri: `wss://your-graphql-endpoint.com/graphql`,
  options: {
    reconnect: true,
  },
});

// src/app/app.component.ts
const NEW_ITEM_SUBSCRIPTION = gql\`
  subscription NewItem {
    newItem {
      id
      name
    }
  }
\`;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  data: any[] = [];

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.apollo.subscribe({
      query: NEW_ITEM_SUBSCRIPTION,
    }).subscribe(({ data }) => {
      this.data.push(data.newItem);
    });
  }
}

Key Points

  • Set up Apollo Client in your Angular project using the ng add apollo-angular command.
  • Configure Apollo Client with your GraphQL endpoint in the GraphQLModule.
  • Use Apollo Client to execute GraphQL queries and mutations in your Angular components.
  • Handle real-time updates by subscribing to GraphQL subscriptions.

Conclusion

Integrating GraphQL with Angular allows you to efficiently fetch and manage data in your applications. By setting up Apollo Client, configuring it with your GraphQL endpoint, and using it to execute queries, mutations, and subscriptions, you can create powerful and responsive Angular applications. Happy coding!