Loading

How to write Graphql Query for Strapi application using Angular

How to write Graphql Query for Strapi application using Angular

Hi Friend, In this Articles, we will learn how to write Graphql Query for Strapi application using Angular.

By default Strapi creates REST endpoints for each of content types. With the help of GraphQL plugin, We can add a GraphQL endpoint to fetch and mutate our content.

So Lets Start

We will cover the below things:

  • Fetch Articles Collection Type with limit & filter option
  • Count Articles with a filter option

Step 1: Create an Article collection with below fields.

Article Collection.PNG

Step 2: Install Graphql Apollo Packages or Add the below packages in you package.json file under dependencies

"apollo-angular": "^1.8.0",
 "apollo-angular-link-http": "^1.9.0",
 "apollo-cache-inmemory": "^1.6.0",
 "apollo-client": "^2.6.10",
 "apollo-link": "^1.2.14",
 "express": "^4.15.2",
 "graphql": "^14.5.0",
 "graphql-tag": "^2.10.0",

Step 3: Create a graphql.module.ts file under app root folder and the below code.

import {NgModule} from '@angular/core';
import {ApolloModule, APOLLO_OPTIONS} from 'apollo-angular';
import {HttpLinkModule, HttpLink} from 'apollo-angular-link-http';
import {InMemoryCache} from 'apollo-cache-inmemory';
import { environment } from 'src/environments/environment';

const uri = environment.apiURL+ '/graphql'; // <-- add the URL of the GraphQL server here
export function createApollo(httpLink: HttpLink) {
 return {
 link: httpLink.create({uri}),
 cache: new InMemoryCache(),
 };
}

@NgModule({
 exports: [ApolloModule, HttpLinkModule],
 providers: [
 {
 provide: APOLLO_OPTIONS,
 useFactory: createApollo,
 deps: [HttpLink],
 },
 ],
})
export class GraphQLModule {}

Step 4: In your app.module.ts Import graphql.module

import { GraphQLModule } from './graphql.module';
imports: [
.......
GraphQLModule,
.......
]

Step 5: Create an articles.js file and write the below code for fetching the data.

import gql from "graphql-tag";

const ARTICLES_QUERY = gql`
 query Articles($start:Int, $limit:Int) {
 articles(start:$start, limit:$limit, sort:"createdAt:desc",where: { status: "published" }) {
 id
 title,
 content,
 publisher,
 published_at,
 slug,
 category {
 id
 name
 slug
 }
 image {
 url
 }
 }
 }
`;

export default ARTICLES_QUERY;

Step 6 create a count_articles.js file and write the below code

import gql from "graphql-tag";

const COUNT_ARTICLES_QUERY = gql`
query {
 articlesConnection(where: { status: "published" }) {
 aggregate {
 totalCount
 }
 }
 }
`;

export default COUNT_ARTICLES_QUERY;

Step 7: Now in your child Component lets write a code for Graphql Query. for this example I am using the home.component.ts

import { isPlatformBrowser } from '@angular/common';
import { Component, OnInit, Inject, PLATFORM_ID } from "@angular/core";
import { Apollo } from "apollo-angular";
import ARTICLES_QUERY from "../article/articles";
import COUNT_ARTICLES_QUERY from "..//article/count_articles"
export class HomeArticlesComponent implements OnInit {
 data: any = {};
 siteURL = environment.siteURL;
 imagePath = environment.imagePath;
 limit: number = 5;
 offset: number = 1;
 totalArticles;
 loading = true;
 errors: any;
 articles: any = [];
 private queryArticles: Subscription;
 private queryCountArticles: Subscription;


 constructor(private apollo: Apollo,
 private router: Router,
 private route: ActivatedRoute, 
 @Inject(PLATFORM_ID) private platform: Object) { }

 ngOnInit() {

this.queryCountArticles = this.apollo
 .watchQuery({
 query: COUNT_ARTICLES_QUERY
 })
 .valueChanges.subscribe(result => {
 this.totalArticles = Object.values(result)[0]['articlesConnection']['aggregate']['totalCount'];

 });

 const page = this.route.snapshot.params.page;
 if( page ) this.page = +page;

 this.getAllArticles(this.page);


}
getAllArticles(offset: number) {

 this.loading = true;
 this.offset = offset
 let start = (this.offset - 1) * this.limit
 this.queryArticles = this.apollo
 .watchQuery({
 query: ARTICLES_QUERY,
 variables: {
 start: start,
 limit: this.limit
 }
 })
 .valueChanges.subscribe(result => {
 this.data = result.data;
 this.articles = this.data.articles; 
 });
 }

 ngOnDestroy() {
 this.queryArticles.unsubscribe();
 }
}

Step 8 in home.component.html let's display the data which we have received through our graphql Query.

<div class="posts inline">
 <article
 *ngFor="let article of articles| paginate: { id: 'server', itemsPerPage: limit, currentPage: offset, totalItems: totalArticles }">
 <div class="imgWrap">
 <a routerLink="/article/{{ article.slug }}" routerLinkActive="active"><img
 src="{{imagePath}}{{ article.image[0].name }}" alt="" alt="{{ article.title }}"></a>
 </div>
 <h1><a routerLink="/article/{{ article.slug}}" routerLinkActive="active">{{ article.title }}</a></h1>
 <div class="postData">
 <div class="iconText"><a routerLink="/article/{{ article.slug}}"><i
 class="far fa-clock"></i>{{article.published_at | date}}</a></div>
 <div class="iconText"><a routerLink="/article/{{ article.slug}}"><i
 class="fas fa-user"></i> {{article.publisher}}</a></div>
 <div class="iconText"><a routerLink="/category/{{ article. category.slug }}"><i class="far fa-list-alt"></i>
 {{article.category.name}}</a></div>
 </div>
 <p> {{ article.content | truncate:100 }}</p>

 </article>

 <div class="has-text-centered"> 
 <pagination-controls (pageChange)="getAllArticles($event)" id="server" ></pagination-controls>
 </div>
</div>

That's It. We have integrated the Graphql WatchQuery. Thanks for reading the article. I hope you like this article.

You May Like Creating a slug system with Strapi, Angular and GraphQl

Related Articles