Initialization

Installation

To get started with Apollo and Angular, install the apollo-client npm package, the apollo-angular integration package, and the graphql-tag library for constructing query documents:

1
npm install apollo-client apollo-angular graphql-tag --save

If you are in an environment that does not have a global fetch implementation, make sure to install a polyfill like whatwg-fetch.

Initialization

To get started using Apollo, we need to create an ApolloClient and use ApolloModule. ApolloClient serves as a central store of query result data which caches and distributes the results of our queries. ApolloModule wires that client into your application.

Creating a client

To get started, create an ApolloClient instance and point it at your GraphQL server:

1
2
3
4
import { ApolloClient } from 'apollo-client';

// by default, this client will send queries to `/graphql` (relative to the URL of your app)
const client = new ApolloClient();

The client takes a variety of options, but in particular, if you want to change the URL of the GraphQL server, you can pass in a custom NetworkInterface:

1
2
3
4
5
6
7
8
import { ApolloClient, createNetworkInterface } from 'apollo-client';

// by default, this client will send queries to `/graphql` (relative to the URL of your app)
const client = new ApolloClient({
networkInterface: createNetworkInterface({
uri: 'http://my-api.grapql.com'
}),
});

The other options control the behavior of the client, and we’ll see examples of their use throughout this guide.

Bootstrap

Angular Modules, also known as NgModules, are the powerful new way to organize and bootstrap your Angular application.

Providing ApolloModule

To connect your client instance to your app, use the ApolloModule.forRoot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { ApolloClient } from 'apollo-client';
import { ApolloModule } from 'apollo-angular';

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

import { AppComponent } from './app.component';

// Create the client as outlined above
const client = new ApolloClient();

export function provideClient(): ApolloClient {
return client;
}

@NgModule({
imports: [
BrowserModule,
ApolloModule.forRoot(provideClient)
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

There is still ApolloModule.withClient available but we recommend you to use ApolloModule.forRoot instead.

Edit on GitHub