Fully functional WhatsApp Clone using Angular, GraphQL, Apollo, TypeScript and PostgreSQL

Fully functional WhatsApp Clone using Angular, GraphQL, Apollo, TypeScript and PostgreSQL

An open-source full-stack example app made with Angular 7.2, TypeScript, GraphQL Subscriptions, GraphQL Code Generator, GraphQL Modules, PostgreSQL and TypeORM.

An open-source full-stack example app made with Angular 7.2, TypeScript, GraphQL Subscriptions, GraphQL Code Generator, GraphQL Modules, PostgreSQL and TypeORM.

You might have seen it around already — an open-source WhatsApp Clone tutorial; a project which was originally started in 2015 by Urigo based on Angular-Meteor and Ionic, and have been throughout different incarnations ever since.

You may have also noticed that we recently published a new React version of the Whatsapp Clone tutorial.

This time around, I’m happy to announce that a new version of the WhatsApp Clone is here, and it’s based on Angular 7.2, Angular CLI 7.3.2, Material-UI, TypeScript, Apollo, GraphQL-Subscriptions, GraphQL Code Generator, GraphQL Modules, PostgreSQL and TypeORM, full with step by step guides to teach you every step of the way.

Click me to go to the tutorial page

We’re back in business!

What is it good for?

This app was built with all the latest and hottest technologies out there. The purpose is simple — it should be a guideline for building a proper app, thus we thought very carefully about the design patterns and architecture used in it, plus, we made sure to cover all communication methods with a GraphQL-back-end in different variations (query, mutation, subscription). This way whenever you’re looking to start a new app, maintain an existing one or upgrade your dev-stack, the WhatsApp-clone can be a great source to start with! It’s full stack and has a complete flow.

Why did we choose this dev-stack?

Angular, GraphQL, Apollo, PostgreSQL and TypeScript for obvious reasons — they are backed by a strong ecosystem that grows rapidly. These technologies can be used in endless variations, and there’s no one way which is the most right of doing so, but we chose a way that makes the most sense for us and that we truly believe in when it comes to building apps. We’ve connected it all with TypeORM, GraphQL-Code-Generator, GraphQL-Modules for the following reasons:

  • The GraphQL back-end was implemented using GraphQL-Modules where logic was splitted into feature based modules. GraphQL-Modules is a library which provides you with the ability to manage and maintain your GraphQL schema in a scalable and reusable way. Not once nor twice I have seen people who struggle with that and get tangled upon their own creation, and with GraphQL-Modules where you have a very defined structure, this problem can be easily solved. You can read more in this series of 7 blog posts about it.
  • Every GraphQL/TypeScript definition was automatically generated with GraphQL-Code-Generator using a single command call. There’s no need to maintain the same thing twice if it already exists in one way or another. This way you don’t have to write TypeScript type definitions for your all your server responses, you get ready-to-use — fully typed Angular services, GraphQL resolvers and GraphQL types.
  • The new version of Angular 7.2 was used with the Angular Material UI and Angular CLI 7.3.2 (and we’ll keep updating the tutorial with the latest versions)
  • We used TypeORM to correctly split the logic of the entities in the database and define the relationships between them. ORMs are controversial these days, but they can help a lot in some cases and we thought a good example could be valuable to the community.

What to expect?

  • The GraphQL back-end was implemented using GraphQL-Modules where logic was splitted into feature based modules. GraphQL-Modules is a library which provides you with the ability to manage and maintain your GraphQL schema in a scalable and reusable way. Not once nor twice I have seen people who struggle with that and get tangled upon their own creation, and with GraphQL-Modules where you have a very defined structure, this problem can be easily solved. You can read more in this series of 7 blog posts about it.
  • Every GraphQL/TypeScript definition was automatically generated with GraphQL-Code-Generator using a single command call. There’s no need to maintain the same thing twice if it already exists in one way or another. This way you don’t have to write TypeScript type definitions for your all your server responses, you get ready-to-use — fully typed Angular services, GraphQL resolvers and GraphQL types.
  • The new version of Angular 7.2 was used with the Angular Material UI and Angular CLI 7.3.2 (and we’ll keep updating the tutorial with the latest versions)
  • We used TypeORM to correctly split the logic of the entities in the database and define the relationships between them. ORMs are controversial these days, but they can help a lot in some cases and we thought a good example could be valuable to the community.

The tutorial goes through every aspect of building the app, starting from the very basics. We will start building a very simple server with a fake db, then we will introduce Authentication, Subscriptions, a real database backed by PostgreSQL and TypeORM plus advanced tooling like GraphQL Code Generator and GraphQL Modules.

This can be extremely useful for those who have little to no background in one of the technologies in our dev-stack.

What’s next?

Right now we implemented a simple REST-based Passport authentication, but we already have PRs[1][2] for Accounts-JS based authentication which will use the GraphQL endpoint instead of traditional REST ones. An additional chapter about Pagination is also expected, as well as a “Performance” chapter tackling the N+1 problem with GraphQL. Our backend has been designed to handle way more features than the ones currently implemented, so be ready because features like the Whatsapp blue ticks are going to land on our clone very soon.

Keep up to date

This tutorial was written using Tortilla — the Tutorial framework.

This means that we will keep upgrading the tutorial with the latest versions of Angular and the other libraries, and instead of doing the same tutorial all over again, you will get a git-diff of how to upgrade the existing tutorial! We care about your time as a developer.

Influence

We want to hear your opinions!

Should we choose another library and technology over another? Could we write the code better/cleaner? Should we add a specific feature to the app? We want to hear it all!

Please tell us now so we could integrate your feedback on the tutorial itself!

We keep evolving the stack and as the tutorial is based on git commits, we can create the same clone with different tech-stacks and compare them on this real app using code diffs.

Soon we will also release yet another version of the Whatsapp Clone, using Ionic, Stencil and Web Components.

If you are good at creating screencast and videos, we would love your help in creating videos for some of the chapters.

Everything is completely free and open source, and we want your help and (not financial) contribution!

Best place would be to open an issue or create a PR on the repositories:

  • The GraphQL back-end was implemented using GraphQL-Modules where logic was splitted into feature based modules. GraphQL-Modules is a library which provides you with the ability to manage and maintain your GraphQL schema in a scalable and reusable way. Not once nor twice I have seen people who struggle with that and get tangled upon their own creation, and with GraphQL-Modules where you have a very defined structure, this problem can be easily solved. You can read more in this series of 7 blog posts about it.
  • Every GraphQL/TypeScript definition was automatically generated with GraphQL-Code-Generator using a single command call. There’s no need to maintain the same thing twice if it already exists in one way or another. This way you don’t have to write TypeScript type definitions for your all your server responses, you get ready-to-use — fully typed Angular services, GraphQL resolvers and GraphQL types.
  • The new version of Angular 7.2 was used with the Angular Material UI and Angular CLI 7.3.2 (and we’ll keep updating the tutorial with the latest versions)
  • We used TypeORM to correctly split the logic of the entities in the database and define the relationships between them. ORMs are controversial these days, but they can help a lot in some cases and we thought a good example could be valuable to the community.

Again, all types of feedback is welcome, write freely!

Thanks for reading ❤

Beginner’s Guide to GraphQL with Angular and Apollo

Beginner’s Guide to GraphQL with Angular and Apollo

In this article, we are going to build a small application using Angular and Apollo client

Originally published by Swathi Prasad at https://techshard.com

GraphQL has been gaining popularity and it has made its way to the forefront of API development. There are several GraphQL clients available today for front-end frameworks. Apollo client is one of the popular clients for Angular applications.

Creating Angular Application

Let’s create a new Angular project using Angular CLI. Run the following command in a terminal or command prompt.

ng new angular-apollo –style=scss –routing=true

I have created project with Angular 8 for this tutorial.

Once the project is created, navigate to the project directory angular-apollo in the command prompt or terminal. Add apollo-angular dependency using the command below.

ng add apollo-angular

This command will add following list of dependencies to the project.

"apollo-angular": "^1.6.0",
   "apollo-angular-link-http": "^1.6.0",
   "apollo-cache-inmemory": "^1.3.2",
   "apollo-client": "^2.6.0",
   "apollo-codegen": "^0.20.2",
   "apollo-link": "^1.2.11",
   "graphql": "^14.3.1",
   "graphql-tag": "^2.10.0"

This command would also create a new file graphql.module.ts. This file can be found under /src/app/. In this file, you will find the below line.

const uri = ''; // <-- add the URL of the GraphQL server here

Add this URL http://localhost:8080/graphql to the above line. This is the GraphQL server endpoint which I created in my previous article.

Accessing GraphQL Mutation endpoints in Angular Apollo

The GraphQL server contains the endpoints for creating and reading data for a Vehicle entity. The process that involves write operations is called Mutation. These operations may involve create, update and delete.

The vehicle data model on the server looks like:

type Vehicle {
       id: ID!,
       type: String,
       modelCode: String,
       brandName: String,
       launchDate: String
}

 The mutation endpoint on the server is as below.

type Mutation {
       createVehicle(type: String!, modelCode: String!, brandName: String, launchDate: String):Vehicle
}

Now, we will access this mutation endpoint using Apollo client.

this.apollo.mutate({
     mutation: gql`mutation {
       createVehicle(type: "car", modelCode: "XYZ0192", brandName: "XYZ", launchDate: "2016-08-16") 
        {
         id
       }
     }`
   }).subscribe(data => {
     //successfully created vehicle entity.
   });

I have added the above code in app.component.ts as below. This is the just a basic example to show how the call is made using Apollo client. Note that, we could use services provided by Apollo client for reusability and maintainability.

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

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

 data: any;

 constructor(private apollo: Apollo) { }

 ngOnInit() {
   this.apollo.mutate({
     mutation: gqlmutation { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;createVehicle(type: "car", modelCode: "XYZ0192", brandName: "XYZ", launchDate: "2016-08-16") &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;id &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
   }).subscribe(data => {
     //successfully created vehicle entity.
   });
 }
}

In this call, we can fetch all the fields from Vehicle object or only a few fields that we need. Here, we are only asking for id field. The server gives back only the id field in the data object.

Querying Data using Apollo Client

As the heading suggests, we will fetch the data using GraphQL query. The query on the server is as follows:

type Query {
       vehicles(count: Int):[Vehicle]
       vehicle(id: ID):Vehicle
}

Using Apollo client, we will access the above the endpoint.

this.apollo.query({
     query: gqlquery { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;vehicles(count: 1) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;modelCode, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;brandName &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
   }).subscribe(({ data, loading }) => {
     this.data = data;
   });

Here, we are interested in only modelCode and brandName fields. The server returns the data with only these fields.

Let’s add a little bit of HTML code to display the data.

 <div class="card" *ngFor="let vehicle of data.vehicles">
   <label class="content">Model: {{ vehicle.modelCode }}</label>
   <label class="content">Brand: {{ vehicle.brandName }}</label>
 </div>
Running the App

Run the application using ng serve. The final app looks like below.


Wrapping Up

We have just scratched the surface of Apollo client. It offers much more features. Check out their documentation for further information.

I hope you enjoyed this article. Let me know if you have any comments or suggestions in the comment section below.

The example for this tutorial can be found on GitHub repository.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

Best 50 Angular Interview Questions for Frontend Developers in 2019

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

A Beginner’s Guide to GraphQL

Node, Express, PostgreSQL, Vue 2 and GraphQL CRUD Web App

Developing and Securing GraphQL APIs with Laravel




Learn GraphQL fundamental with Angular 8 and Apollo Example

Learn GraphQL fundamental with Angular 8 and Apollo Example

In this tutorial, we'll teach you about the fundamental GraphQL concepts starting with an introduction and then explaining the building blocks for a GraphQL API. Next, we'll see how to build an example Angular 8 app that consumes a GraphQL API from scratch using Apollo client.

In this tutorial, we'll teach you about the fundamental GraphQL concepts starting with an introduction and then explaining the building blocks for a GraphQL API. Next, we'll see how to build an example Angular 8 app that consumes a GraphQL API from scratch using Apollo client.

We'll be consuming a GraphQL API built with Node.JS and Express.

In a nutshell, you'll understand:

  • What is GraphQL and why using it to build web APIs instead of REST,
  • What is the difference between a Schema-first-approach vs. a Code-first-approach,
  • What is a Schema and how to use it to define the structure of the data in your API,
  • What's a Schema Definition Language (SDL) and how can be used to define a Schema,
  • What's a builtin scalar type and how to use it to create object types,
  • What are object types and how they are used to define a Schema,
  • Root types such as queries, mutations, and subscriptions,
  • What's a resolver function,
  • How to map resolvers to fields in the root types of a Schema,
  • How to make executable Schemas to actually create a GraphQL API.

For the practical example, we'll learn how to:

  • Install Angular CLI 8
  • Create an Angular 8 app
  • Creating an Angular component for displaying consumed GraphQL API data
  • Install and set up Angular Apollo using the ng add command
  • Connect Angular Apollo to our GraphQL API server built with Node.JS and Express
  • Consume the GraphQL API from our Angular component using Angular Apollo service
Do You Need to Learn how to Build a GraphQL API?

As far as Angular is concerned, you only need to know how to consume a GraphQL API not how to build it, but if you want to take it further,

Angular is not a server-side framework, so it can't be used to build web APIs with GraphQL but as an Angular developer, most often than not, you would need to consume an API which may be, very well, written in GraphQL as the technology became very popular in the recent years.

As a frontend developer, you are not required to know about server-side technologies like GraphQL but will definitively help you to better communicate with the backend team/developer if you know the fundamental concepts of GraphQL.

Note: GraphQL has been open-sourced and released as an open-source specification, so the GraphQL API server can be developed in any server-side programming language that you know including TypeScript (On top of Node.js).

What is GraphQL?

GraphQL stands for Graph Query Language.

The official website defines GraphQL as:

A query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

So, GraphQL is a query language (In the same sense as SQL is a query language) but not for databases, instead it's designed for querying data over the HTTP protocol and creating an API in the same way REST is used but with more advantages.

It's also a runtime that provides the actual mechanisms for processing the API queries and returning data and responses.

GraphQL allows you to provide a complete description of the data used in your application. As a result, clients will be able to query for the exact data that they need no less, no more. If you used REST before, you can imagine how powerful the GraphQL approach is.

GraphQL was originally created by Facebook and later open-sourced. Nowadays, more companies are using it ranging from IBM and GitHub to Twitter and PayPal.

Advantages of GraphQL

According to the official website, these are the advantages of GraphQL:

  • Ask for what you need, get exactly that.
  • Get many resources in a single request.
  • Describe what’s possible with a type system.
  • Move faster with powerful developer tools like Graph_i_QL.

Since you can describe the exact data that you need to fetch from your API server, you can send only a single HTTP request for multiple resources instead of many requests in the case of REST.

This means you'll have less network overhead and more performance.

When using REST, things may become tedious and error-prone for complex data requirements but with GraphQL, you can have nested queries which make it easy to get related data without trying to figure out how much requests you need to send and in what order. You may even end up failing to get the desired data if a proper endpoint is not present in the backend in the case of REST but not with GraphQL.

What is a GraphQL Schema?

A GraphQL schema is a fundamental concept around which you can build your API.

The first step of building a GraphQL API is the definition of the schema. You can consider a schema as a blueprint for all of the data that you can return in your API.

The schema describes the data types and the relationships between them. It also defines the possible queries that can be used to fetch data and what mutations can be used to create and update data.

A schema may contain types and their fields, queries, mutations, and subscriptions. a type can be either an object type or builtin scalar.

Additional information can be added as custom directives.

You need to include at most one schema definition when using the type system definition language.

In this example, a GraphQL schema is defined with both query and mutation root types:

schema {
  query: QueryRootType
  mutation: MutationRootType
}

What is an SDL?

GraphQL provides its own Schema Definition Language or SDL which provides an agnostic way to define a GraphQL schema no matter what programming language is used.

Schema-first-approach vs. Code-first-approach

You can write a GraphQL API in one of two approaches, a schema first approach or code first approach. The latter approach is more tied to a specific implementation provided by a programming language since you need to use code to define your GraphQL schema.

In a schema-first approach, we write our schema in the GraphQL SDL language and we call some methods to execute it. We then need to map resolvers (the methods that actually implement the queries and mutations) to fields. This is the leading approach in the GraphQL community.

In a schema-first approach, you write your data types, queries and mutations in the schema first then you add the implementation using resolvers.

This offers many benefits, for example, it allows frontend developers to start building the UI based on the schema before it's implemented by backend developers.

GraphQL Scalar and Object Types

In GraphQL, types are en essential concept. In fact, everything in the schema is a type even queries and mutations.

Queries, mutations, and subscriptions are called root types.

The basic elements of a GraphQL schema are object types, which define a type of object you can fetch from your API, and what fields it has. We create the object types out of the builtin scalar types.

GraphQL provides various built-in scalar types defined by the specification such as:

  • ID,
  • String,
  • Int,
  • Float,
  • Boolean

It also allows you to create object types for describing the structure of your data.

You can define a type using the type keyword:

type Employee {
  id: ID!
  name: String
  phone: String
  address: String
  emails: [String]
}

Employee is an object type, created using the builtin scalar types. It doesn’t provide any functionality except defining the structure or shape of our employee model in the application/database.

It's composed of fields. A field has a name and a type:

name: String

Note: In addition to scalar types, a field can use any other type defined in the schema definition.

You can make the field non-nullable by adding an exclamation mark, as follows:

id: ID!

You can define list fields using square brackets around the type:

emails: [String]

To implement the API, you will need to add fields to the root types (Queries, Mutations, and Subscriptions) of the GraphQL schema. These types define the entry points for the GraphQL API.

GraphQL Enums

An enum allows you to define a type that has a predefined set of possible values. For example:

enum Category {
  CAT1
  CAT2
}

GraphQL Interfaces

An interface is comprised of a list of fields and can be implemented by a GraphQL type which must have the same fields as the implemented interface:

interface Person {
  name: String!
}

You can use the implements keyword to implement the interface:

type Employee implements Person {
}

What is a GraphQL Query Type?

A GraphQL query is a root type that defines the shape of the queries that can be accepted by the API server. For example:

type Query {
  empolyee(id: ID!): Employee
}

This root type exposes an employee field that takes an ID and returns an Employee.

Note: The root types of a schema define the shape of the queries and mutations that will be permitted by the API server. This enables GraphQL to provide a concise contract for client-server communication.

What is a GraphQL Mutation Type?

Mutations are root types that are used to create, update or delete data. They are similar to the PUT, POST, PATCH and DELETE operations in REST APIs.

We use the Query root type to define the entry-points for operations used to fetch data and the Mutation root type to add the entry points for the operations to create, update and delete data.

For example:

type Mutation {
  addEmployee(name: String, phone: String, emails: String[], address: String): Employee
}

Here we add a single addEmployee mutation which accepts the name, phone, emails and address arguments (also called input types) and returns the created Employee object.

What is a GraphQL Resolver?

When you build GraphQL APIs, the process is centered around the schema. The process is generally as follows:

  • You create the schema definition,
  • And you implement the actual operations using the resolver functions.

GraphQL makes a separation between the structure and behaviour.

The structure is defined with the schema. You then need to write an implementation that provides the behavior of the fields in the root types. This is done with what's called a resolver function which needs to be provided for each field in the root types.

A question that arises is how to map the resolver functions to the fields?

This can be done in many approaches. In the code-first approach, you have objects that you can use to define fields and resolvers in the same place. See graphene-js or express-graphql for JavaScript.

In the schema first approach, you can't add resolvers directly in the schema, but you have various APIs (available from different packages such as GraphQL.js and graph-tools) to map the resolvers after defining your schema such as:

  • Using the buildSchema() method which is available from the GraphQL.js package,
  • Using the makeExecutableSchema() method of the graphql-tools package.
Consuming a Node.js GraphQL API with Angular 8 and Apollo

Let's now see how to consume a Node.js GraphQL API built in this tutorial using Angular 8 and Apollo.

Installing Angular CLI 8

Before we can initialize our Angular project, we need to install Angular CLI. Make sure you have Node.JS and NPM installed on your development machine and open a new terminal then run the following command:

$ npm install -g @angular/cli

That's it, we are ready to create our Angular project and consume a GraphQL API.

Creating an Angular 8 App

Let's start by generating our Angular 8 application. Open a new terminal and run the following command:

$ ng new angular-graphql-example

You'll be prompted if you would like to add routing to your project and which stylesheets format would you like to use. You can answer yes for routing and CSS for stylesheets.

Next, navigate to your project's folder and serve your app using the following commands:

$ cd angular-graphql-example
$ ng serve

Your application will be available from http://localhost:4200.

Creating an Angular Component for Displaying GraphQL API Data

We'll be consuming a Node.js GraphQL API for an employees database, so we don't need many components in our application. We already have the App component which we can use for displaying our GraphQL API data, but let's create a component and add a route for it in the router configuration for best practices. Open a new terminal anf run the following commands:

$ cd angular-graphql-example
$ ng generate component employees

Next, open the src/app/app-routing.module.ts file and add a route for the employees component to the router configuration:

import { EmployeesComponent } from './employees/employees.component';

const routes: Routes = [
  {
    path: 'employees',
    component: EmployeesComponent
  }
]

We can now access the component from the http://localhost:4200/employees path.

Installing Apollo for Angular 8

We'll be making use of Apollo with Angular 8 to consume the GraphQL API, so we'll need to run the following command for setting up Apollo in our project:

$ ng add apollo-angular

apollo-angular enables you to fetch data from your GraphQL server and use it for building complex and reactive UIs using the Angular framework. Apollo Angular may be used in any context that Angular may be used.

Connecting Angular Apollo to our GraphQL API server

Now, we can connect our Angular components with the GraphQL server for consuming data. Open the src/app/graphql.module.ts file and update the uri variable with your GraphQL URL as follows:

const uri = 'https://repl.it/@techiediaries/Node-GraphQL-Example/graphql'; // <-- add the URL of the GraphQL server here

That's all what we need to connect our Angular 8 application with our Node.js GraphQL server.

Consuming GraphQL APIs with Angular Apollo Service

Let's proceed to consuming the GraphQL API using the Apollo service. Open the src/app/employees/employees.component.ts file and add the following imports:

import { Apollo, QueryRef } from 'apollo-angular';
import gql from 'graphql-tag';

Next, before the component definition, add the following GraphQL query:

const EMPLOYEES_QUERY = gql`
  query {
    employees {
        id,
        name,
        email,
        phone,
        address
    }
  }
`;

The gql tag allows you to create a GraphQL query object from a template string.

Next, update the component as follows to send a GraphQL query when the component is initialized:

@Component({
  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {

  employees: any[] = [];

  private query: QueryRef<any>;

  constructor(private apollo: Apollo) {}

  ngOnInit() {
    this.query = this.apollo.watchQuery({
      query: EMPLOYEES_QUERY,
      variables: {}
    });

    this.query.valueChanges.subscribe(result => {
      this.employees = result.data && result.data.employees;
    });
  }

}

In the ngOnInit() method we call the apollo.watchQuery() method to initialize data fetching. Next, we subscribe to any data changes using the valueChanges.subscribe() method and we set the employees array with the data consumed from the GraphQL server.

Conclusion

In this tutorial, we've introduced you to the fundamental GraphQL concepts such as: - Schemas, - Scalar and object types, - Queries, mutations, and subscriptions, - Resolvers.

We have seen the difference between the schema first approach and code first approach for creating GraphQL APIs. How you can make an executable schema using methods like buildSchema() and makeExecutableSchema() from the GraphQL.js and graph-tools packages.

Next, we have created a GraphQL client application with Angular 8 and Apollo for consuming a GraphQL API server built with Node.JS and Express.

How to Consume a GraphQL API with Angular

How to Consume a GraphQL API with Angular

In this article, we will show you how to use Angular to Consume a GraphQL API.

To download the source code, visit the Consuming a GraphQL API with Angular Source Code.

For the complete navigation of this tutorial visit GraphQL ASP.NET Core Tutorial.

Preparing the Angular Project

After we have finished with the ASP.NET Core client app, let’s create an Angular app as well.

We are going to start by creating a new Angular project without navigation module and with CSS as default styles. As soon as creation is over, we are going to install a set of libraries required for the Apollo Client to work with Angular:

npm install apollo-angular apollo-angular-link-http apollo-client apollo-cache-inmemory graphql-tag graphql -- save

The next step is to modify app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ApolloModule } from 'apollo-angular';
import { HttpLinkModule } from 'apollo-angular-link-http';
import { HttpClientModule } from '@angular/common/http';
 
import { AppComponent } from './app.component';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ApolloModule,
    HttpLinkModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We import the ApolloModule and HttpLinkModule files, required for the Appolo integration with Angular. But, we can see that HttpClientModule is included as well. That’s because in order to work properly, HttpLinkModule internally uses HttpClientModule.

Let’s move on.

In the same way that we created model files for the ASP.NET Core client application, we are going to create them here.

So, let’s create a new folder „types“ and inside several type files:

export type OwnerInputType = {
    name: string;
    address: string;
}


export type AccountType = {
    'id': string;
    'description': string;
    'ownerId' : string;
    'type': string;
}


import { AccountType } from './accountType';
 
export type OwnerType = {
    'id': string;
    'name': string;
    'address': string;
    'accounts': AccountType[];
}

Now, we can create a graphql.service.ts file and modify it as well:

import { Injectable } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import { OwnerType } from './types/ownerType';
import { OwnerInputType } from './types/ownerInputType';
 
@Injectable({
  providedIn: 'root'
})
export class GraphqlService {
  public owners: OwnerType[];
  public owner: OwnerType;
  public createdOwner: OwnerType;
  public updatedOwner: OwnerType;
 
  constructor(private apollo: Apollo, httpLink: HttpLink) {
    apollo.create({
      link: httpLink.create({ uri: 'https://localhost:5001/graphql' }),
      cache: new InMemoryCache()
    })
  }
}

We have an instance of the Apollo service with all the required configuration (link and cache). Both properties are required and must be populated.

After these configuration actions, we are ready to create some queries.

Creating Queries and Mutations

Let’s modify the graphql.service.ts file, by adding our first query:

public getOwners = () => {
    this.apollo.query({
      query: gql`query getOwners{
      owners{
        id,
        name,
        address,
        accounts{
          id,
          description,
          type
        }
      }
    }`
    }).subscribe(result => {
      this.owners = result.data as OwnerType[];
	console.log(this.owners);
    })
  }

We are using the Apollo service with its query function to write the entire GraphQL query. We’re using the imported gql tag as well, in order to be able to write GraphQL code as a multi-line string.

Now, let’s modify the app.component.ts file in order to test this query:

import { Component, OnInit } from '@angular/core';
import { GraphqlService } from './graphql.service';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements OnInit{
 
  constructor(private service: GraphqlService) {
  }
 
  ngOnInit(): void {
    this.service.getOwners();
  }
  title = 'angulargraphqlclient';
}

As soon as we start the Angular application, we can inspect the result:

Excellent.

Here are all the other queries and mutations from the graphql.service.ts file:

Get by Id Query
public getOwner = (id) => {
    this.apollo.query({
      query: gql`query getOwner($ownerID: ID!){
      owner(ownerId: $ownerID){
        id,
        name,
        address,
        accounts{
          id,
          description,
          type
        }
      }
    }`,
      variables: { ownerID: id }
    }).subscribe(result => {
      this.owner = result.data as OwnerType;
    })
  }


Create mutation example
public createOwner = (ownerToCreate: OwnerInputType) => {
    this.apollo.mutate({
      mutation: gql`mutation($owner: ownerInput!){
        createOwner(owner: $owner){
          id,
          name,
          address
        }
      }`,
      variables: {owner: ownerToCreate}
    }).subscribe(result => {
      this.createdOwner = result.data as OwnerType;
    })
  }


Update mutation example
public updateOwner = (ownerToUpdate: OwnerInputType, id: string) => {
    this.apollo.mutate({
      mutation: gql`mutation($owner: ownerInput!, $ownerId: ID!){
        updateOwner(owner: $owner, ownerId: $ownerId){
          id,
          name,
          address
        }
      }`,
      variables: {owner: ownerToUpdate, ownerId: id}
    }).subscribe(result => {
      this.updatedOwner = result.data as OwnerType;
    })
  }


Delete mutation example
public deleteOwner = (id: string) => {
    this.apollo.mutate({
      mutation: gql`mutation($ownerId: ID!){
        deleteOwner(ownerId: $ownerId)
       }`,
      variables: { ownerId: id}
    }).subscribe(res => {
      console.log(res.data);
    })
  }

You can test them by modifying the app.component.ts file, or if you want to create a new component to consume all these results.

Conclusion

We have learned a lot of great stuff about GraphQL and its integration with ASP.NET Core. Of course, with these last two articles, we went even further, by creating two client applications to consume our GraphQL app.

We hope you have enjoyed this tutorial and if you have any suggestions or question, don’t hesitate to leave a comment in the comment section. If you liked this post, share it with all of your programming buddies!

Further reading

☞ A Beginner’s Guide to GraphQL

Building a Secure API with GraphQL & Spring Boot

Building A GraphQL API With Nodejs And MongoDB

☞ GraphQL with React: The Complete Developers Guide

☞ How to create a simple CRUD App using GraphQL and Node.js

☞ Node, Express, PostgreSQL, Vue 2 and GraphQL CRUD Web App

☞ Developing and Securing GraphQL APIs with Laravel


Originally published on code-maze.com