Angular Integration Guide

A simple, type-safe integration for JustCMS in your Angular project

Features Overview

JustCMS Angular Integration provides a robust set of features designed to make content management seamless in your Angular applications. Let's explore the main capabilities that make this integration powerful and developer-friendly.

TypeScript Support

Fully typed structures for all API responses ensuring type safety

Angular Service Integration

Pre-built injectable service that handles all JustCMS API communications

Easy Configuration

Simple setup through Angular's dependency injection system

Flexible Endpoints

Comprehensive API coverage for categories, pages, and menus

These features work together to provide a seamless development experience while ensuring your content management needs are met efficiently and reliably. The integration is designed to scale with your project, whether you're building a small website or a large-scale application.

Installation Guide

Setting up JustCMS in your Angular project is straightforward and requires just a few simple steps. Follow this guide to get started with the integration.

Required Files

First, you'll need to add two essential configuration files to your project:

just-cms.config.ts

Contains configuration interfaces and injection tokens

just-cms.service.ts

Provides the main service for interacting with JustCMS API

Dependencies

The JustCMS integration relies on Angular's HTTP client module. Make sure you have it installed in your project.

npm install @angular/common

Installation Steps

Step 1: Copy Configuration Files

Add just-cms.config.ts and just-cms.service.ts to your project

Step 2: Install Dependencies

Ensure @angular/common/http is installed

Step 3: Import HTTP Module

Add HttpClientModule to your AppModule imports

After completing these steps, you'll need to configure your API credentials. This involves providing your JustCMS API token and project ID through Angular's dependency injection system.

Verification

To verify your installation was successful, check that:

  • Both configuration files are present in your project structure
  • @angular/common/http is listed in your package.json dependencies
  • HttpClientModule is properly imported in your AppModule

Once these steps are completed, you can proceed with configuring your JustCMS credentials and start using the service in your components.

Configuration Setup

Setting up JustCMS in your Angular application is straightforward through Angular's dependency injection system. You'll need to provide your API token and project ID to get started.

Step-by-Step Configuration

Import Required Modules

Make sure to import necessary Angular modules and JustCMS configuration files

Configure API Details

Set up your JustCMS API token and project ID

Update App Module

Add the configuration to your Angular application's providers

First, ensure you have the JustCMS configuration files in your project. The main configuration happens in your AppModule where you'll provide the API credentials.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { JUST_CMS_CONFIG, JustCmsConfig } from './just-cms.config';

const justCmsConfig: JustCmsConfig = {
  apiToken: 'YOUR_JUSTCMS_API_TOKEN',
  projectId: 'YOUR_JUSTCMS_PROJECT_ID'
};

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    { provide: JUST_CMS_CONFIG, useValue: justCmsConfig }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The configuration involves three key components:

  • The HttpClientModule for making API requests
  • The JUST_CMS_CONFIG injection token
  • Your JustCMS credentials in the justCmsConfig object

Important Configuration Notes

Secure Credentials

Store API tokens in environment files, not directly in code

Required Modules

Ensure HttpClientModule is imported for API communication

Type Safety

Use the provided JustCmsConfig interface for type checking

For better security, it's recommended to store your API credentials in environment files:

// environment.ts
export const environment = {
  production: false,
  justCms: {
    apiToken: 'YOUR_JUSTCMS_API_TOKEN',
    projectId: 'YOUR_JUSTCMS_PROJECT_ID'
  }
};

// app.module.ts
import { environment } from './environments/environment';

const justCmsConfig: JustCmsConfig = {
  apiToken: environment.justCms.apiToken,
  projectId: environment.justCms.projectId
};

Once configured, the JustCMS service will be available throughout your application through dependency injection. You can inject it into any component or service that needs to interact with JustCMS content.

Basic Usage of JustCmsService

Using JustCmsService in your Angular components is straightforward. First, you'll need to inject the service into your component and then use its methods to fetch data from JustCMS. Let's look at some practical examples.

Component Setup

To start using JustCmsService in your component, follow these basic steps:

  1. Import the necessary types and service
  2. Inject the service into your component
  3. Call the service methods to fetch data
  4. Handle the responses in your template
import { Component, OnInit } from '@angular/core';
import { JustCmsService, Category } from './just-cms.service';

@Component({
  selector: 'app-categories',
  template: `
    <div>
      <h2>Categories</h2>
      <ul>
        <li *ngFor="let cat of categories">
          {{ cat.name }}
        </li>
      </ul>
    </div>
  `
})
export class CategoriesComponent implements OnInit {
  categories: Category[] = [];

  constructor(private justCmsService: JustCmsService) { }

  ngOnInit(): void {
    this.justCmsService.getCategories().subscribe({
      next: (cats) => this.categories = cats,
      error: (err) => console.error('Error fetching categories', err)
    });
  }
}

Service Injection

Inject JustCmsService through the constructor for dependency injection

Type Safety

Use provided interfaces like Category for better type checking

Error Handling

Always implement error handling for API calls

Async Data

Use Angular's async pipe or subscribe to handle Observable responses

Error Handling Best Practices

When working with JustCmsService, it's important to implement proper error handling. Here's an example of a more robust implementation:

export class CategoriesComponent implements OnInit {
  categories: Category[] = [];
  loading = false;
  error: string | null = null;

  constructor(private justCmsService: JustCmsService) { }

  ngOnInit(): void {
    this.loading = true;
    this.justCmsService.getCategories().subscribe({
      next: (cats) => {
        this.categories = cats;
        this.loading = false;
      },
      error: (err) => {
        this.error = 'Failed to load categories';
        this.loading = false;
        console.error(err);
      }
    });
  }
}

Using with Angular Template

Here's how you can display the data in your template with loading and error states:

<div class="categories-container">
  <ng-container *ngIf="!error; else errorTpl">
    <div *ngIf="loading">Loading categories...</div>
    <ul *ngIf="!loading">
      <li *ngFor="let category of categories">
        {{ category.name }}
      </li>
    </ul>
  </ng-container>
  
  <ng-template #errorTpl>
    <div class="error-message">
      {{ error }}
    </div>
  </ng-template>
</div>

Loading States

Always show loading indicators for better user experience

Error Messages

Display user-friendly error messages when API calls fail

Conditional Rendering

Use ngIf directives to manage different component states

Available Service Methods

The JustCmsService provides several core methods to interact with your JustCMS content. Each method is fully typed and returns an Observable with the appropriate response type.

getCategories()

This method retrieves all categories associated with your JustCMS project. It returns an Observable of Category array.

// Simple usage
this.justCmsService.getCategories().subscribe(categories => {
  // categories is of type Category[]
  console.log(categories);
});

getPages()

The getPages method allows you to fetch pages with flexible options for filtering and pagination. It accepts an optional parameters object.

filters

Optional PageFilters object for filtering results by category

start

Optional number to specify the starting index for pagination

offset

Optional number to specify how many items to return

// Get all pages
this.justCmsService.getPages().subscribe(response => {
  console.log(response.items); // array of pages
  console.log(response.total); // total count
});

// Get filtered pages
this.justCmsService.getPages({
  filters: { category: { slug: 'blog' } },
  start: 0,
  offset: 10
}).subscribe(response => {
  // Handle paginated and filtered results
});

getPageBySlug()

This method retrieves detailed information about a specific page using its slug identifier. It accepts an optional version parameter for fetching specific content versions.

// Basic usage
this.justCmsService.getPageBySlug('about-us').subscribe(page => {
  // page is of type PageDetail
});

// With version specified
this.justCmsService.getPageBySlug('about-us', 'draft').subscribe(page => {
  // Handle specific version
});

getMenuById()

Use this method to fetch a menu and its items by providing the menu's unique identifier. The response includes the complete menu structure with all items and their relationships.

this.justCmsService.getMenuById('main-menu').subscribe(menu => {
  // menu is of type Menu
  console.log(menu.items); // Access menu items
});

Type Safety

All methods provide full TypeScript support for response types

Observable Returns

Each method returns an Observable for reactive programming

Error Handling

Use error callback in subscribe for proper error management

When using these methods, remember to properly handle errors and unsubscribe from observables when your component is destroyed to prevent memory leaks. It's recommended to use the async pipe in templates when possible for automatic subscription management.

Utility Functions

JustCMS Angular integration provides several utility functions to help you work with content blocks, images, and categories more efficiently. These helper methods simplify common operations and make your code more readable and maintainable.

Content Block Utilities

The isBlockHasStyle method allows you to check if a content block has a specific style applied to it. This is particularly useful when you need to apply conditional formatting or behavior based on block styles.

// Check if a block has 'highlight' style
const isHighlighted = this.justCmsService.isBlockHasStyle(block, 'highlight');

Image Handling Utilities

getLargeImageVariant

Retrieves the large variant of an image from the variants array

getFirstImage

Gets the first image from an image block including alt text and variants

Image utilities help you manage different image variants and extract image information from content blocks. These methods are particularly useful when working with responsive images or different image sizes.

// Get large image variant
const largeImage = this.justCmsService.getLargeImageVariant(page.coverImage);

// Get first image from an image block
const firstImage = this.justCmsService.getFirstImage(imageBlock);

Category Utilities

The hasCategory utility function helps you check if a page belongs to a specific category. This is useful for filtering content or applying category-specific logic in your templates.

// Check if page belongs to 'blog' category
const isBlogPost = this.justCmsService.hasCategory(page, 'blog');

Type Safety

All utility functions are fully typed with TypeScript for better development experience

Easy Integration

Methods are available directly through the JustCmsService instance

Performance

Utilities are optimized for efficient content manipulation

These utility functions are designed to make common content management tasks easier and more efficient. They handle edge cases and provide type safety while maintaining clean and readable code. Remember that all these methods are available through your injected JustCmsService instance.