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.
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.
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 { createVehicle(type: "car", modelCode: "XYZ0192", brandName: "XYZ", launchDate: "2016-08-16") { id } }
}).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.
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 { vehicles(count: 1) { modelCode, brandName } }
}).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>
Run the application using ng serve. The final app looks like below.
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
☞ 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
#angular #apollo #graphql #database #web-development