A simple, type-safe integration for JustCMS in your Angular project
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.
Fully typed structures for all API responses ensuring type safety
Pre-built injectable service that handles all JustCMS API communications
Simple setup through Angular's dependency injection system
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.
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.
First, you'll need to add two essential configuration files to your project:
Contains configuration interfaces and injection tokens
Provides the main service for interacting with JustCMS API
The JustCMS integration relies on Angular's HTTP client module. Make sure you have it installed in your project.
npm install @angular/common
Add just-cms.config.ts and just-cms.service.ts to your project
Ensure @angular/common/http is installed
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.
To verify your installation was successful, check that:
Once these steps are completed, you can proceed with configuring your JustCMS credentials and start using the service in your components.
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.
Make sure to import necessary Angular modules and JustCMS configuration files
Set up your JustCMS API token and project ID
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:
Store API tokens in environment files, not directly in code
Ensure HttpClientModule is imported for API communication
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.
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.
To start using JustCmsService in your component, follow these basic steps:
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)
});
}
}
Inject JustCmsService through the constructor for dependency injection
Use provided interfaces like Category for better type checking
Always implement error handling for API calls
Use Angular's async pipe or subscribe to handle Observable responses
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);
}
});
}
}
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>
Always show loading indicators for better user experience
Display user-friendly error messages when API calls fail
Use ngIf directives to manage different component states
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.
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);
});
The getPages method allows you to fetch pages with flexible options for filtering and pagination. It accepts an optional parameters object.
Optional PageFilters object for filtering results by category
Optional number to specify the starting index for pagination
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
});
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
});
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
});
All methods provide full TypeScript support for response types
Each method returns an Observable for reactive programming
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.
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.
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');
Retrieves the large variant of an image from the variants array
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);
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');
All utility functions are fully typed with TypeScript for better development experience
Methods are available directly through the JustCmsService instance
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.