Zone configuration for Angular SPA

To show the personalized content on a zone of your Angular-based Single-Page Application (SPA), you must subscribe the zone to Acoustic Personalization.

Prerequisites

  • Install and configure the Personalization Library.
    For more information, see Installing the Personalization Library for SPA.
  • Ensure that you register zones with the same Zone Id in Zone registration page of Acoustic Personalization and on the channel.

📘

Important

As a best practice, the updates to Personalization Library should first be validated in a non-Production environment before upgrading the Production website.
To subscribe the zones of your Angular Single-Page Application (Angular SPA), complete these steps:

The code snippets shown here are only for guidance and should be modified to include the rendering logic to display the content.

Zone configuration using Stable version (1.5.0)

Complete the Step (1) only once for your channel. Step (2) onwards must be done for each zone that you want to personalize.

  1. Add the following imports in app.module.ts file or the root module file.
import {PersonalizationModule} from '@acoustic/personalization';

Add the PersonalizationModule.forRoot({}) in the imports array of @NgModule().

@NgModule({
   imports: [ 
    ...
    PersonalizationModule.forRoot({})
    ...
   ],
})
  1. Identify the zones on your channel that you want to personalize.
  2. Add the following imports in the component file to which the identified zone belongs.
import {of, throwError, concat} from 'rxjs';
import {map, catchError } from 'rxjs/operators';
import {NgPersonalization} from '@acoustic/personalization';
  1. Use the following code snippet to import and inject the NgPersonalization and other dependencies in the constructor of the component:
constructor(private personalizationService: NgPersonalization) {}
  1. Create a variable resultObservable$ that subscribes to the observable that is returned from Personalization Library.
    Copy the following code snippet and paste it in the ngOnInit() function.
this.personalizationService.onReady(()=>{           
      this.resultObservable$ = this.personalizationService.getContentId("<<Zone ID>>")
            .pipe(
                map(id => id === 'DCIDNF404' ? '<<defaultContent>>' : id),
                catchError(error => {
                    console.log('Error', 'Rule not matched from SPA');
                    return concat(of('defaultContent'), throwError(error));
                })
            );

In the code snippet:

  • Replace <<Zone ID>> as a parameter. For more information about the zone ID, see Registering a zone
  • Replace <<defaultContent>> with the default content that you want to display on the channel if no rules match the user behavior.
  • The error code DCIDNF404 is returned when no published rules are available or when none of the published rules match the visitor behavior on the channel. In such case, Acoustic Personalization does not return any personalized content. The channel must handle this scenario by specifying a default content to be displayed.

For more information about error codes, see Personalization Library response codes

If the zones that you want to personalize are in the same component, include them in the same onReady function.
If the zones that you want to personalize are in different components, create a separate onReady function for each component.
6. Repeat Steps (3) through Steps (5) for each zone that you want to personalize.
7. Render the content returned by Acoustic Personalization.

Example code

this.personalizationService.onReady(()=>{         
            this.resultWelcomeBanner$ = this.personalizationService.getContentId('WelcomeBannerZone')
            .pipe(
                map(id => id === 'DCIDNF404' ? '906bb0b5-bf17-45c5-89e7-ce0c58300a03' : id),
                catchError(error => {
                    console.log('Error', 'Rule not matched from SPA');
                    return concat(of('cddcefc7-6227-483b-8fd7-63a45c6fd244'), throwError(error));
                })
            );

        this.resultFeature$ = this.personalizationService.getContentId('FeatureLayoutZone')
            .pipe(
                map(contentId => contentId === 'DCIDNF404' ? 'cab6e657-bee0-4635-b9a4-d76ea3292483' : contentId),
                catchError(error => {
                console.log('Error', 'Rule not matched from SPA');
                return concat(of('cab6e657-bee0-4635-b9a4-d76ea3292483'), throwError(error));
                })
            ); 
        
        });

Zone configuration using Latest version

You can use this procedure for the personalization library versions 2.0.0, 2.1.0, and 2.2.0.

Updates to app.module.ts

Perform the following steps in the file app.module.ts

  1. Add the following code to import the Personalization Library.
import { PersonalizationLibrary } from “@acoustic/personalization”;
  1. Initialize the Personalization Library inside the constructor of the application’s RootModule.
export class AppModule { 
    constructor() {
        PersonalizationLibrary.create();
    }
}
  1. Add the imported personalization object PersonalizationLibrary into the providers array as shown below. This enables the personalization service to be shared and used across the client application.
providers: [
   PersonalizationLibrary
.
.
.
]

Changes to target.component.ts

Identify the component where the personalization/ recommendation is to be added, and make the following updates.

  1. Add the following import to use the personalization object as a service in the target component of the client application.
import {PersonalizationLibrary} from ‘@acoustic/personalization’;
  1. Add the imported member into the constructor.
constructor(private personalizationObject: PersonalizationLibrary) {}
  1. Configure the zone.
    The switch case shown below illustrates the processing for various content types. The following content types are currently supported:
  • recommendation
  • custom-url
  • custom-html
  • wch-html
  • wch-url
  • "" : To be used when the content returned is a default content.

If needed, you can add the processing for other content types as per your requirement.

function personalizationHandler(result) {
            switch(result.type) {
                case "recommendation": 
                    return displayRecommendations(result);
                case "custom-url":
                    return displayCustomUrl(result);
                case "custom-html":
                    return displayCustomHtml(result);
                case "wch-url":
                    return displayWchUrl(result);
                case "wch-html":
                    return displayWchHtml(result);
                case "":
                    return displayDefaultContent(result);
            }
        }

Definitions of the helper functions

The following code snippet provides the definitions of helper functions inside the personalizationHandler() function.

displayDefaultContent(content) {
    // return the default content
}

function displayDefaultHTMLContent(content) {
    // return the default HTML content
}

function displayCustomHtml(content) {
    let contentId = content.value
    if (contentId && contentId !== 'CONNF404') {
        // return the personalized html content
    } else {
        displayDefaultHTMLContent(content);
    }
}

function displayWchHtml(content) {
    let contentId = content.value
    if (contentId && contentId !== 'CONNF404') {
        // return the personalized html content
    } else {
        displayDefaultHTMLContent(content);
    }
}

function displayCustomUrl(content) {
    let contentId = content.value;
    if (contentId && contentId !== "CONNF404") {
        // return the personalized content
    } else {
        // return the default content
        displayDefaultContent(content);
    }
    
}

function displayWchUrl(content) {
    let contentId = content.value;
    if (contentId && contentId !== "CONNF404") {
        // return the personalized content
    } else {
        // return the default content
        displayDefaultContent(content);
    }
    
}

function displayRecommendations(products) {
    let recommendations = products.value;
    if (recommendations && recommendations !== "CONNF404") {
        // return the personalized recommendations
    } else {
        // return the default recommendations
        return displayDefaultContent(products);
    }
}
  1. Configure the personalized zones.
this.personalizationObject.onReady(()=>{
this.personalizationObject.getContent({ zoneId:‘<ZoneRegId>’, num: <numberofproducts>[OPTIONAL]})
.then(
result => {
            this.VARIABLE_NAME = personalizationHandler(result);
        // VARIBLE_NAME can be used to display the contents
    }
)
});

Changes in the HTML file

Locate the HTML file of your SPA zone on which you want to show content personalization or product recommendations. Add the following snippet to it.

<div id=”<ZoneRegId>” wrtp-recommended-zone=”<ZoneRegId>”>
     <div *ngIf=”<VARIABLE_NAME>”></div> // Make use of this variable to display and render the contents
</div>

In the code snippet:

  • Replace <<Zone ID>> with the registered ID of the zone you want to personalize. For more information about the zone ID, see Registering a zone
  • Replace <<defaultContent>> with the default content that you want to display on the channel if no rules match the user behavior.
  • The error code CONNF404 is returned when no published rules are available or when none of the published rules match the visitor behavior on the channel. In such case, Acoustic Personalization does not return any personalized content. The channel must handle this scenario by specifying a default content to be displayed.

For more information about error codes, see Personalization Library response codes

If the zones that you want to personalize are in the same component, include them in the same onReady function.
If the zones that you want to personalize are in different components, create a separate onReady function for each component.

Next steps

After you have configured the zones of your channel, you can implement the following features:

Capture the click events on zones

You can configure the zones to capture the click events, so as to track the effectiveness of your personalized content. Capturing the click events is essential to generate the performance reports for the personalization.
For more information, see Capture click events

Configure geolocation

Configuring geolocation enables you to display personalized content based on the visitor's geographical location. For more information, see Configure Geolocation

Display header for your recommendation zone

When creating a product recommendations strategy, you can optionally specify the header (title) to be displayed on each zone. This makes it easier for you to communicate the objective of each recommendation strategy to your website visitors. For more information, see Display header for recommendation zone