Build a Minimal Site in Angular with Headless Oracle Content Management
Introduction
Angular is a platform for building mobile and desktop web applications.
To consume our Oracle Content Management content in an Angular application, we can use the Angular minimal sample available as an open-source repository on GitHub.
In this tutorial, we’ll build a simple minimal site in Angular by leveraging Oracle Content Management as a headless CMS as well as its software development kit (SDK) for content delivery in JavaScript. This Angular sample is available on GitHub.
The tutorial consists of three steps:
- Prepare Oracle Content Management
- Build the minimal site in Angular
- Prepare your application for deployment
Prerequisites
Before proceeding with this tutorial, we recommend that you read the following information first:
To follow this tutorial, you’ll need:
- an Oracle Content Management subscription
- an Oracle Content Management account with the Content Administrator role
- a Windows or Mac computer with Node version 10 or higher
What We’re Building
With Angular minimal, you can easily retrieve images and other content from your Oracle Content Management repository.
To take a look at what we’re building, here’s the end state of our tutorial, a basic Angular minimal site that consumes content from Oracle Content Management:
https://headless.mycontentdemo.com/samples/oce-angular-minimal-sample
This is what the home page will look like at the end of this tutorial:
This is what the contact us page will look like at the end of this tutorial:
To proceed, you’ll need to have an active subscription to Oracle Content Management and be logged in with the Content Administrator role.
Task 1: Prepare Oracle Content Management
If you don’t already have an Oracle Content Management instance, see the Quick Start to learn how to register for Oracle Cloud, provision an Oracle Content Management instance, and configure Oracle Content Management as a headless CMS.
For this tutorial, you’ll need to create a content model. There’s a downloadable asset pack available that will fill your empty repository with content types and associated content.
To prepare Oracle Content Management:
- Create a channel and asset repository.
- Create a content model using either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Create a Channel and Asset Repository
You first need to create a channel and an asset repository in Oracle Content Management so you can publish content.
To create a channel and an asset repository in Oracle Content Management:
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Publishing Channels from the selection list in the page header.
In the upper right corner, click Create to create a new channel. Name the channel ‘OCEMinimalChannel’ for the purpose of this tutorial, and keep the access public. Click Save to create the channel.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header.
In the upper right corner, click Create to create a new asset repository. Name the asset repository ‘OCEMinimalRepository’ for the purpose of this tutorial.
In the Publishing Channels field, select the OCEMinimalChannel channel to indicate to Oracle Content Management that content in the OCEMinimalRepository repository can be published to the OCEMinimalChannel channel. Click Save when you’re done.
Create a Content Model
The next step is to create a content model. You can use either of two methods:
- Method 1: Import the Oracle Content Management Samples Asset Pack
- Method 2: Create your own content model
Import the Oracle Content Management Samples Asset Pack
You can download a preconfigured Oracle Content Management sample assets pack that contains all required content types and assets for this tutorial. If you prefer, you can also create your own content model rather than download the sample assets pack.
You can upload a copy of the content we’re using in this tutorial from the Oracle Content Management Samples Asset Pack. This will let you experiment with the content types and modify the content. If you want to import the Oracle Content Management Samples Asset Pack, you can download the asset pack archive, OCESamplesAssetPack.zip, and extract it to a directory of your choice:
Download the Oracle Content Management Samples Asset Pack (OCESamplesAssetPack.zip) from the Oracle Content Management downloads page. Extract the downloaded zip file to a location on your computer. After extraction, this location will include a file called OCEMinimal_data.zip.
Log in to the Oracle Content Management web interface as an administrator.
Choose Content in the left navigation menu and then choose Repositories from the selection list in the page header. Now select OCEMinimalRepository and click the Import Content button in the top action bar.
Upload OCEMinimal_data.zip from your local computer to the Documents folder.
Once it’s uploaded, select OCEMinimal_data.zip and click OK to import the contents into your asset repository.
After the content has been imported successfully, navigate to the Assets page and open the OCEMinimalRepository repository. You’ll see that all the related images and content items have now been added to the asset repository.
Click Select All on the top left and then Publish to add all the imported assets to the publishing channel that you created earlier, OCEGettingStartedChannel.
Before publishing, you need to validate all the assets. First add OCEMinimalChannel as a selected channel, and then click the Validate button.
After the assets have been validated, you can publish all the assets to the selected channel by clicking the Publish button in the top right corner.
Once that’s done, you can see on the Assets page that all assets have been published. (You can tell by the icon above the asset name.)
After importing the Oracle Content Management Samples Asset Pack, you can start building the Minimal Site in React.
Create Your Own Content Model
Instead of importing the Oracle Content Management Samples Asset Pack, you can also create your own content model.
For this tutorial, we’re using a content type called ‘MinimalMain’ as the main content type for this sample. This content type consists of header and footer logos, and a list of pages that should be included on the nav.
To create content types for the content model:
- Log in to the Oracle Content Management web interface as an administrator.
- Choose Content in the left navigation menu and then choose Asset Types from the selection list in the page header.
- Click Create in the top right corner.
- Choose to create a content type (not a digital asset type). Repeat this for all required content types.
We’ll create three content types, each with its own set of fields:
- MinimalMain
- MinimalPage
- MinimalSection
The first content type, MinimalMain, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
headerLogo | Single-value media field | headerLogo | |
footerLogo | Single-value media field | footerLogo | |
pages | Multiple-value reference field | pages |
This is what your MinimalMain content type definition should look like:
The second content type, MinimalPage, should have the following field:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
sections | Multiple-value reference field | sections |
This is what your MinimalPage content type should look like:
The third and final content type, MinimalSection, should have the following fields:
Display Name | Field Type | Required | Machine Name |
---|---|---|---|
type | Single-value text field | X | type |
heading | Single-value text field | heading | |
body | Single-value large-text field | body | |
image | Single-value image field | image | |
actions | Single-value embedded content field | actions |
This is what your MinimalSection content type should look like:
Once you’ve created your content types, you can add these content types to the repository that you created earlier, OCEMinimalRepository:
- Log in to the Oracle Content Management web interface as an administrator.
- Navigate to OCEMinimalRepository.
- Edit the repository and, under Asset Types, specify all three newly created content types. Click the Save button to save the changes.
After adding the content types to the repository, you can open the OCEMinimalRepository repository on the Assets page and start creating your content items for all the content types.
Task 2: Build the Minimal Site in Angular
To consume our Oracle Content Management content in a server-side rendered Angular application, we can use the Angular minimal site sample, which is available as an open-source repository on GitHub.
Note: Remember that using the Angular sample is optional, and we use it in this tutorial to get you started quickly. You can also build your own Angular application.
To build the minimal site in Angular:
- Clone the sample repository and install dependencies
- Configure the Angular application
- Work with the Oracle Content Management Content SDK
- Use the Content SDK to Fetch Content
Clone the Sample Repository and Install Dependencies
The Angular minimal site sample is available as an open-source repository on GitHub.
You’ll first need to clone the sample from GitHub to your local computer and change your directory into the repository root:
git clone https://github.com/oracle/oce-angular-minimal-sample.git
cd oce-angular-minimal-sample
Now that you have your code base, you need to download dependencies for the application. Run the following command from the root directory:
npm install
Configure the Angular Application
In this Angular minimal site sample, you need to configure a few pieces of information so that your Oracle Content Management Content SDK (and any other requests) can target the correct instance URL and API version with the correct channel token. These values are used in src/scripts/server-config-utils.js to instantiate a new delivery client.
This application uses an .env file that is read by Webpack when it bundles the client and server applications. By using webpack.DefinePlugin, any values read from the .env file can be made available to anywhere in the application.
Open the .env file in a text editor. You’ll see the following:
# The connection details for the Oracle Content Management server to be used for this application
SERVER_URL=https://samples.mycontentdemo.com
API_VERSION=v1.1
CHANNEL_TOKEN=ba0efff9c021422cb134c2fd5daf6015
Change each key-value pair to reflect your instance URL, the API version you want to target, and the channel token associated with your publishing channel. The channel for this tutorial is OCEMinimalChannel.
Work with the Oracle Content Management Content SDK
Oracle Content Management offers an SDK to help discover and use content in your applications. The SDK is published as an NPM module, and the project is hosted on GitHub.
Learn more about the SDK here.
The SDK has been registered as a runtime dependency of this project in the package.json file.
Use the Content SDK to Fetch Content
We can now leverage the Content SDK to fetch content so that we can render it in our Angular application.
The Content SDK uses a DeliveryClient object to specify the endpoint. You can make all requests using that client object.
The src/scripts folder contains the code for getting data from Oracle Content Management using the Content SDK.
The src/scripts/server-config-utils.js file imports the Content SDK and then creates a delivery client using the configuration specified in .env.
The following command imports the SDK:
import { createDeliveryClient, createPreviewClient } from '@oracle/content-management-sdk';
The following command creates the delivery client:
return createDeliveryClient(serverconfig);
The src/scripts/services.js file contains functions to get the data for this React minimal application.
The fetchOceMinimalMain() method retrieves the content type MinimalMain with a slug of minimalmain.
export async function fetchOceMinimalMain() {
const data = await getItem('minimalmain', 'fields.headerlogo,fields.footerlogo,fields.pages');
if (!data.hasError) {
const { fields } = data;
const { headerlogo, footerlogo } = fields;
// Extract the sourceset for the headerImage and footerImage and put it back in the data
.headerRenditionURLs = getSourceSet(headerlogo);
data.footerRenditionURLs = getSourceSet(footerlogo);
data
}return data;
}
For rendering the images, the services.js provides a helper method to retrieve the sourceset for an asset that is constructed from the renditions for the asset.
function getSourceSet(asset) {
const urls = {};
.srcset = '';
urls.jpgSrcset = '';
urlsif (asset.fields && asset.fields.renditions) {
.fields.renditions.forEach((rendition) => {
assetaddRendition(urls, rendition, 'jpg');
addRendition(urls, rendition, 'webp');
;
})
}// add the native rendition to the srcset as well
.srcset += `${asset.fields.native.links[0].href} ${asset.fields.metadata.width}w`;
urls.native = asset.fields.native.links[0].href;
urls.width = asset.fields.metadata.width;
urls.height = asset.fields.metadata.height;
urlsreturn urls;
}
The fetchPage() method retrieves the content type MinimalPage using the slug value for the page obtained from the previous query.
export async function fetchPage(pageslug) {
// Get the page details
const page = await getItem(pageslug, 'fields.sections');
return page;
}
The getRenditionURLs() method retrieves the rendition urls for any image that may be defined in a section using the id for that image. This call is done client side.
export function getRenditionURLs(identifier) {
const client = getClient();
return client.getItem({
id: identifier,
expand: 'fields.renditions',
.then((asset) => getSourceSet(asset))
}).catch((error) => logError('Fetching Rendition URLs failed', error));
}
Now that we have our data query, we can render the responses in our Angular components.
Client-Side Versus Server-Side Rendering
With client-side rendering (CSR), the client is responsible for building and rendering the content of a web page using JavaScript. With server-side rendering (SSR), the whole page is built on the server, and a complete web page is returned to the client.
When the web page is requested from the server in client-side rendering, the HTML document returned contains skeleton HTML and no actual content. It contains a reference to a JavaScript bundle, which the client then requests from the server. On receiving this bundle, the client executes the JavaScript and populates the web page. Until the client has finished executing the JavaScript, all the user sees is a blank web page. One downside of client-side rendered applications is that when some web crawlers index the site, there is no actual content to index.
With server-side rendering (SSR), the whole page is built on the server, and a complete web page is returned to the client. The advantage of this is that web crawlers can index the entire content on the web page.
Angular Server-Side Rendering
The flow of the Angular image gallery application is as follows:
- The client makes a request to the server for a given route.
- The Express server receives the request.
- The Express server passes all client requests for pages to Angular Univeral’s Express Engine
- Angular Univeral’s Express Engine takes a template HTML file and populates it with the following
- The markup for the given route
- The route data serialized out
- References to any stylesheets
- References to JavaScript bundles to run on the client
- The Express server returns the HTML document created by Angular Univeral’s Express Engine to the client
- The client receives the HTML and renders it. The user will see a fully formed web page.
- The client requests any JavaScript bundles from the server. After receiving it, the client runs the JavaScript in the bundle.
- It “hydrates” the HTML, adding in any client-side JavaScript such as event listeners.
- Angular automatically takes the serialized data from the page and injects it into the JavaScript code to be available to the components
- If the HTML document contained a style sheet, the client requests the style sheet.
Angular CLI supports adding server-side rendering support to an existing Angular application. See https://angular.io/guide/universal for further details.
Server-Side Express Server
The server application makes use of an Express server to receive the request and forward on to Angular Univeral’s Express Engine.
The Express server file is located at server.js. This file is created by the Angular CLI when adding server side rendering support.
Angular Components
Angular components are written in TypeScript and define a template that defines the view. These templates contain ordinary HTML, Angular directives, and binding markup, which enable Angular to adjust the HTML before it is rendered.
The next few sections provide an overview of how Angular renders our application in each of our components:
- App Module
- Root Module for Server-Side Rendering
- Page Data Resolver
- App Component
- Header, and Footer Components
- Section Component
- PageComponent
App Module
The app module located in src/app/app.module.ts. It bootstraps the application with the App component.
This file defines the different routes for our application. In our site, we want to provide two routes: - the root path (/) - and a page path (/page/:slug)
The root route is redirected to the page route with no page slug specified. The page route define the resolver PageDataResolver, used to get all of the data required for the route before the route’s components are created.
Open the root component, located at src/app/app.module.ts, and see the routes defined:
const appRoutes: Routes = [
// no path specified, go to home
{path: '',
redirectTo: '/page/',
pathMatch: 'full',
runGuardsAndResolvers: 'always',
,
}
{path: 'page/:slug',
component: PageComponent,
resolve: { routeData: PageDataResolver },
runGuardsAndResolvers: 'always',
,
}; ]
This app module is the entry point when rendering the application on the client side.
Root Module for Server-Side Rendering
The main entry point to this Angular application, when rendering the application on the server, is the app server module located in src/app/app.server.module.ts.
This module imports the app module, located in src/app/app.server.module.ts, along with Angular’s ServerModule. The server-side application bootstraps the same App component as the client and uses all the same components.
The Angular CLI creates the server module file when adding server side rendering support.
Page Data Resolver
The page data resolver, located in src/resolvers/page-data.resolver.ts, handles getting the data to render in the pages.
When the client is hydrating, this data is obtained from the transferState that was populated during the server-side rendering and serialized out into the HTML document returned to the client.
During server-side rendering, or client-side rendering when client-side navigation has occurred, the transferState will not contain the data. The data is obtained from the Oracle Content Management server using the Content SDK.
return fetchOceMinimalMain()
.then((appData) => {
if (pageSlug === null || pageSlug === '') {
= appData.fields.pages[0].slug;
pageSlug
}return fetchPage(pageSlug).then((pageData) => {
if (isPlatformServer(this.platformId)) {
// add the two pieces of data to the transfer state separately
this.transferState.set(APP_KEY, appData);
this.transferState.set(PAGE_KEY, pageData);
}
// return the two pieces of data in a single object
const fullData = { appData, pageData };
return fullData;
;
}); })
App Component
The App component, located in src/app/app.component.ts, defines the root view.
This component contains the router-link tags. Angular will swap components on and off the page within those tags, based on the current route.
Header, and Footer Components
The Header and Footer components are used the Page component to display the header and footer respectively.
The header data is passed to the Header component, located at src/app/header/header.component.ts, and the footer data is passed to the Footer component, located at src/app/footer/footer.component.ts. the Header and Footer components simply use the data passed to them; they do not get any additional data from the server. See the bindings in src/app/header/header.component.html and src/app/footer/footer.component.html.
Section Component
The Section component, located at src/app/section/section.component.ts, is used by Page component and is used to render any content items of the type MinimalSection.
This component has data passed to it from the Page component and if the section data has an image, it makes a client side call to get the rendition urls for the image from the server.
ngOnInit() {
this.heading = this.section.fields.heading;
this.type = this.section.fields.type;
// sanitize the content for html display
const content = this.section.fields.body;
const options = {
stripIgnoreTag: true, // filter out all HTML not in the whitelist
stripIgnoreTagBody: ['script'],
;
}this.body = filterXSS(content, options);
this.actions = this.section.fields.actions;
if (this.section.fields.image) {
getRenditionURLs(this.section.fields.image.id).then((urls) => {
this.renditionURLs = urls;
;
})
} }
Page Component
The Page component is responsible for rendering the header, footer and all the sections defined for a page.
Open the Page component, located at src/app/page/page.component.ts. In ngOnInit you can see that the component gets the data from the active route, which was populated by the home page resolver.
ngOnInit() {
const fullData = this.route.snapshot.data.routeData;
this.appData = fullData.appData;
this.headerRenditionURLs = this.appData.headerRenditionURLs;
this.footerRenditionURLs = this.appData.footerRenditionURLs;
this.pageData = fullData.pageData;
if (!this.pageData.hasError) {
this.sections = this.pageData.fields.sections;
this.pages = this.appData.fields.pages;
} }
The markup for the Page component is located at src/app/page/page.component.html.
Task 3: Prepare Your Application for Deployment
Now that we’ve built our Angular minimal site, we need to see it in a local development server so we can debug any issues and preview the application before it goes live.
Prepare the application for deployment in two steps:
Spin Up a Local Development Server
You can start a development server locally by running the following command.
npm run dev
Then, open your browser to http://localhost:4200 to see your site in action.
Test Your Application in the Production Environment
For production the build script would be used to build the client and server code.
Use the following command to run the build script:
npm run build
This script first runs the client build and then runs the server build.
Deploy the built dist/server and dist/browser on the server machine before you start the application. Then use the following command to start it:
npm run start
Conclusion
In this tutorial, we created a minimal site in Angular, which can be found on GitHub. This site uses Oracle Content Management as a headless CMS. After setting up and configuring Oracle Content Management with a channel of published content for the minimal site tutorial, we installed and ran the Angular site to fetch the required content and build the site.
For more information on Angular, go to the Angular website.
Learn about important Oracle Content Management concepts in the documentation.
You can find more samples like this on the Oracle Content Management Samples page in the Oracle Help Center.
Build a Minimal Site in Angular with Headless Oracle Content Management
F39534-01
December 2021
Copyright © 2021, Oracle and/or its affiliates.
Primary Author: Oracle Corporation