Consuming a GraphQL API with Angular
This post is about consuming a GraphQL API with an Angular application. For this post I am using a Azure Function with GraphQL - I already wrote a blog post - Create Azure Functions with GraphQL Support.
I created the Azure function using the HotChocolate Templates. You can install the template using
dotnet new -i HotChocolate.Templates command. And then create the function using
dotnet new graphql-azf command. In the function code, I added the Query class and here is the whole function code.
Here is the
Query.cs class file.
And finally here is the
Now we are ready with the Azure Function, we can run it using
func start --cors "*" --csharp command. The CORS flag is required otherwise Angular will not able to access the GraphQL endpoint.
Next let us create an Angular Application. For demo purposes I am creating it like this -
ng new App --minimal --skip-tests. This will create an Angular application with the name
App. Next we need to add different packages which required to consume GraphQL endpoint, we are using a client package
Apollo Angular. We can run this command to install the packages -
npm install apollo-angular @apollo/client graphql. In their documentation they mentioned to install this using
ng add apollo-angular, but due to some reason it didn’t worked for me.
Next we need to modify the
tsconfig.json, we need to include
compilerOptions if it not available. It is required because the
@apollo/client package requires
AsyncIterable. And next we need to modify the
app.module.ts like this.
httpLink.create method, we need to configure the GraphQL endpoint - our Azure Function endpoint. Now we can use the Apollo service in the angular components. In this post I am querying the graphql endpoint. In the
app.component.ts, we can write code like this.
In this code, the apollo service is injected via constructor and consumed in the
ngOnInit. We can use the
gql object to create queries. Both
gql classes are part of
apollo-angular module which should be included in the code. And the data can be displayed in the UI using the
ngFor. Here is an example.
This way GraphQL can be consumed in Angular. Other GraphQL operations can be implemented similar way. Subscriptions maintain a persistent connection, they can’t use the default HTTP transport that Apollo Client uses for queries and mutations. Instead, Apollo Client subscriptions most commonly communicate over WebSocket, via the community-maintained
Happy Programming :)