GraphQL is a query language created by Facebook. It allows us to describe the data in our API using a schema definition language. It uses a typed query system. We get exactly the data we ask for, and nothing more. It represents your API as a graph. Nodes are objects, and edges are the relationships between them.
1 . Set Up Angular Project: Create a new Angular project using Angular CLI
ng new my-graphql-app
cd my-graphql-app
2 . Install Dependencies: Install apollo-angular library with Angular Schematics
ng add apollo-angular
After hitting this command, you’ll be required to enter your GraphQL server’s URL. The countries API, a fantastic public endpoint for data about nations, continents, and languages, will be used in this example.
Visit trevorblades.com to see it.
? Url to your GraphQL API https://countries.trevorblades.com? Version of GraphQL 16
CREATE src/app/graphql.module.ts (670 bytes)
UPDATE package.json (1135 bytes)
UPDATE tsconfig.json (857 bytes)
UPDATE src/app/app.module.ts (462 bytes)
- Installing packages (npm)...
The aforementioned screenshot illustrates how the script generates a new module named graphql.module.ts and automatically updates all other files with the required imports and configurations.
This is how the graphql.module.ts file should appear:
import { APOLLO_OPTIONS, ApolloModule } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { NgModule } from '@angular/core';
import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core';
const uri = ' https://countries.trevorblades.com'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
return {
link: httpLink.create({ uri }),
cache: new InMemoryCache(),
};
}
@NgModule({
exports: [ApolloModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {}
3 . Create the Interface:
We will now make two basic interfaces: one for the continent and one for the country. Our data from the API will eventually be stored in these two objects.
import { Continent } from "./continent"
export interface Country {
name : string
capital : string
currency : string
emoji : string
phone : string
continent : Continent
}
export interface Continent {
name : string
}
4 . Create a New Countries Service:
The next step is to construct a CountriesService that all application classes can use to retrieve the nations once we’ve created our interfaces. Later on, we will inject it into the CountriesComponent constructor using the dependency injection that Angular provides.
With the CLI, you may create a new Angular service by running the command listed below:
ng g service countries
Now, open the generated countries.service.ts file and place the following code:
import { Injectable } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';
import { Observable, map } from 'rxjs';
import { Country } from '../interface/country';
// write a GraphQL query that asks for information (name , capital, etc..) about all countries
const COUNTRIES = gql`
{
countries {
name
capital
currency
emoji
phone
continent {
name
}
}
}
`;
@Injectable({
providedIn: 'root'
})
export class CountriesService {
constructor(private apollo: Apollo) { }
getCountries(): Observable<Country[]> {
return this.apollo.watchQuery<any>({query: COUNTRIES,}).valueChanges.pipe(map((result) => result.data.countries));
}
}
The next step is to construct a CountriesService that all application classes can use to retrieve the nations once we’ve created our models. Later on, we will inject it into the CountriesComponent constructor using the dependency injection that Angular provides.
With the CLI, you may create a new Angular service by running the command listed below:
Related read: Angular Setup and CRUD Operations: A Comprehensive Guide
5 . Create a New Countries Component:
Now, let’s generate a new component using the below command:
ng g c countries
Add the selector to the app.component.html file:
<app-countries></app-countries>
Open the countries.component.ts file and paste the following code:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { CountriesService } from '../../core/services/countries.service'
@Component({
selector: 'app-countries',
templateUrl: './countries.component.html',
styleUrls: ['./countries.component.scss']
})
export class CountriesComponent implements OnInit{
@ViewChild(MatPaginator) paginator: MatPaginator | any;
@ViewChild(MatSort) sort: MatSort | any;
displayedColumns: string[] = [
'name',
'capital',
'currency',
'emoji',
'phone',
'continent',
];
dataSource!: MatTableDataSource<any>;
constructor(private countriesService: CountriesService) {}
ngOnInit() {
this.countriesService.getCountries().subscribe(data => {
this.dataSource = new MatTableDataSource(data);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
});
}
}
🔸 displayedColumns: The names of the data table columns that will be shown.
🔸 dataSource$: The nations we previously retrieved from the server are included in the observable. The countriesService, which is injected into the component’s constructor, is where we are calling the getCountries() function.
6 . Add Angular Material:
We will be using Angular material’s data table component to display the data in this example.
Type the following command to add the library to your project:
ng add @angular/material
We need to import MatTableModule, MatPaginatorModule, and MatSortModule in app.module.ts.
7 . Display the Countries in the Datatable:
In the HTML file, place the following code:
<div class="style">GraphQL in Angular</div>
<div class="mat-elevation-z8 mt">
<table mat-table [dataSource]="dataSource" matSort>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
<td mat-cell *matCellDef="let row">{{ row.name }}</td>
</ng-container>
<!-- Capital Column -->
<ng-container matColumnDef="capital">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Capital</th>
<td mat-cell *matCellDef="let row">{{ row.capital }}</td>
</ng-container>
<!-- Currency Column -->
<ng-container matColumnDef="currency">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Currency</th>
<td mat-cell *matCellDef="let row">{{ row.currency }}</td>
</ng-container>
<!-- Emoji Column -->
<ng-container matColumnDef="emoji">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Emoji</th>
<td mat-cell *matCellDef="let row">{{ row.emoji }}</td>
</ng-container>
<!-- Phone Column -->
<ng-container matColumnDef="phone">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Phone</th>
<td mat-cell *matCellDef="let row">+{{ row.phone }}</td>
</ng-container>
<!-- Continent Column -->
<ng-container matColumnDef="continent">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Continent</th>
<td mat-cell *matCellDef="let row">{{ row.continent.name }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator
[pageSizeOptions]="[5, 10, 20]"
showFirstLastButtons
aria-label="Select page of periodic elements"
>
</mat-paginator>
</div>
Result:
We learned how to rapidly set up GraphQL in an Angular application with this easy tutorial. When installing and configuring dependencies, the Angular diagrams save time when compared to doing it all yourself. By embracing GraphQL and leveraging tools like Apollo Angular, we’ve streamlined our development process and enhanced our application’s capabilities.
As we conclude, let’s continue exploring GraphQL’s potential to optimize data retrieval and management, ensuring our Angular applications remain efficient and scalable.
We worked with Mindbowser on a design sprint, and their team did an awesome job. They really helped us shape the look and feel of our web app and gave us a clean, thoughtful design that our build team could...
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork