Angular + Prepr CMS

This is the official Angular + Prepr guide. It’ll explain to you how to quickly install and configure Prepr’s JavaScript SDK, and fetch data from the Prepr CMS using it.

Getting started

In this guide, you’ll learn how to create an Angular app capable of fetching and using data from the Prepr CMS.

Prerequisites

This guide assumes that you’ve:

  • An active Prepr account.
  • Set-up an environment on Prepr CMS, preferably using the demo content provided by Prepr. This can be done by clicking on Load demo content when setting up the environment.
  • Angular CLI installed on your system.

If you don’t have the Angular CLI installed, you can install it using the following command:

npm install -g @angular/cli

Creating a new Angular project

You can skip this step if you already have an existing Angular project.

To begin, create a new Angular project using ng new :

ng new prepr-angular

Once created, navigate to the project’s directory using cd prepr-angular. Here you can test whether your Angular app is working fine using ng serve. Once started, you should be able to view your app at http://localhost:4200/.

Before adding and configuring the Prepr’s JavaScript SDK, you need to install an additional package, i.e. @types/node, using the following command:

npm install -save-dev @types/node

Open tsconfig.json from the root directory of your project and add the following two options under angularCompilerOption:

"types": ["node"],
"typeRoots": ["../node_modules/@types"]

Creating Prepr Client

Close the server you started in the above step and add the Prepr’s Javascript SDK to your app by using the following command:

npm install @preprio/nodejs-sdk

Create a prepr.ts file inside the src directory of your project using the following commands:

touch src/prepr.ts

You’ll use this file to create and configure your Prepr client with the help of createPreprClient provided by the SDK. This client will be used to make API requests to endpoints provided by the Prepr CMS across your Angular application.

Add the following code to this file:

const { createPreprClient } = require('@preprio/nodejs-sdk');
import { environment } from 'src/environments/environment';

export const prepr = createPreprClient({
 token: environment.prepr_access_token, // You can find one in your environment
 baseUrl: “https://graphql.prepr.io/graphql”,
 userId: null, // Optional, used for AB testing implementations
});

Prepr recommends using environment variables to store your sensitive information like access token. To add environment variables, open /src/environments/environment.ts and add it as a new property to the existing environment object as shown below:

export const environment = {
 production: false,
 prepr_access_token: '<your access token>',
};

Creating a Prepr service and fetching data

Now, let’s make use of the Prepr client you created above to fetch some data from the CMS.

If you’re using the same preloaded demo content in your CMS environment as mentioned above in the Prerequisites section, you should have 5 posts in there. Let’s try to fetch their ids and titles. For this you’ll make use of the following GraphQL query:

{
 posts: Posts {
   items {
       title
   }
 }
}

But how do you know if this is the right query? To test your queries, you can make use of Explorer provided under Apollo Studio’s sandbox mode. There you can easily create queries with the help of the documentation pane and check the results in real time. All you’ll need is your unique graphql endpoint, All the necessary information about the endpoint can be found here.

Let’s create a service for fetching the posts data. Go to the root directory of your project and run the following command:

ng g service prepr

Change the content of newly created service, src/app/prepr.service.ts, with the code below:

import { Injectable } from '@angular/core';
import { Post } from './post';
import { prepr } from '../prepr';

@Injectable({
 providedIn: 'root',
})
export class PreprService {
 constructor() {}

 async fetchPosts() {
   try {
     const data = await prepr
       .graphqlQuery(
         `{
             posts: Posts {
               items {
                   _id
                   title
               }
           }
         }`
       )
       .fetch();
     const posts: Post[] = data.data.posts.items;
     return {
       posts,
     };
   } catch (error) {
     throw error;
   }
 }
}

Create a post.ts file under the src/app/ directory of your project using the following commands:

cd src/app
touch post.ts

Add the following Post interface to this file which will be used for mapping the response received from the Prepr CMS.

export interface Post {
 _id: string;
 title: string;
}

Now, open src/app/app.module.ts and configure it for the new newly created prepr.service.ts as shown below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { PreprService } from './prepr.service';

@NgModule({
 declarations: [AppComponent],
 imports: [BrowserModule, AppRoutingModule],
 providers: [PreprService],
 bootstrap: [AppComponent],
})
export class AppModule {}

Finally, open src/app/app.component.ts and replace its content with the following code:

import { Component, OnInit } from '@angular/core';
import { Post } from './post';
import { PreprService } from './prepr.service';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
 title = 'prepr-angular';
 posts: Post[] = [];

 constructor(private preprService: PreprService) {}

 ngOnInit(): void {
   this.getPosts();
 }

 private async getPosts() {
   try {
     const response = await this.preprService.fetchPosts();
     this.posts = response.posts;
     console.log(this.posts);
   } catch (error) {
     console.log(error);
   }
 }
}

In the above code, you’re adding a new getPosts method which makes you of the Prepr client, via Prepr service you created above, to fetch post ids and titles from the CMS. After running the application, when visiting your local Angular server in the browser, you should be able to see the posts array consisting of post ids and titles in the console panel accessible via inspect mode as shown in the image below:

Angular filter

Displaying data

Let’s get rid of the console log statements in src/app/app.component.ts and actually display the titles in your app.

Open src/app/app.component.html and replace it’s content with the code below:

<div>
 <p *ngFor="let post of posts; let i = index">{{ post.title }}</p>
</div>

Once done, when visiting your local Angular server in the browser, you should see the following output:

Angular local

Learn More

For additional information on using @preprio/nodejs-sdk, check out its documentation.