Concepts / Building Search UI / Plug analytics
Feb. 21, 2019

Plug analytics

You are reading the documentation for Angular InstantSearch v3, which is in beta. You can find the v2 documentation here.

Using Algolia Insights with Angular InstantSearch

This guide describes how to use Algolia Insights with Angular InstantSearch.

Loading and initializing the library

Insights library can be either loaded via jsDelivr CDN or directly bundled with your application. We recommend loading the library by adding the snippet below to your main HTML file.

1
2
3
4
5
6
7
8
9
<script>
  !function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e.aa=e.aa||function(){(e.aa.queue=e.aa.queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],i.async=1,i.src="https://cdn.jsdelivr.net/npm/search-insights@1.0.0",c.parentNode.insertBefore(i,c)}(window,document,"script",0,"aa");

  // Initialize library
  aa('init', {
    appId: 'APPLICATION_ID',
    apiKey: 'SEARCH_API_KEY'
  });
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  config = {
    appId: "APPLICATION_ID",
    apiKey: "SEARCH_API_KEY",
    indexName: "demo_ecommerce"
  };

  clickedObjectIDsAfterSearch(props) {
    (window as any).aa('clickedObjectIDsAfterSearch', props)
  }
  convertedObjectIDsAfterSearch(props) {
    (window as any).aa('convertedObjectIDsAfterSearch', props)
  }
}

Enabling queryID response

To enable the queryID response from the search API, Angular InstantSearch enables setting custom query parameters with the ais-configure widget:

1
<ais-configure [searchParameters]="{ clickAnalytics: true }"></ais-configure>

Reporting click and conversion events

When you want to trigger a click event depends on your implementation type and business logic. A good framework would be to send a click event once a user has clicked on something that indicates action inside the hit - for example, when a user clicks on a result (for click events) or when a user adds an item to a cart (for conversions).

This example covers how to obtain the objectID and position values for reporting. This feature is not available with the built-in widgets. But you can compose the connectors to create a new component that will have access to these values. You gonna use the ais-hits for access the hits and there positions;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<ais-hits>
  <ng-template let-hits="hits" let-results="results">
    <div *ngFor="let hit of hits; index as i" class="ais-Hits-item">
      <ais-highlight attribute="name" [hit]="hit"></ais-highlight>
      <button
        class="btn"
        (click)="
          clickedObjectIDsAfterSearch({
            eventName: 'Add to Cart',
            index: 'instant_search',
            queryID: results.queryID,
            objectIDs: [hit.objectID],
            positions: [results.hitsPerPage * results.page + i + 1]
          })
        "
      > Favorite </button>
    </div>
  </ng-template>
</ais-hits>

Or your conversion event:

1
2
3
4
5
6
7
8
9
10
11
<button
    class="btn"
    (click)="
      convertedObjectIDsAfterSearch({
        eventName: 'Add to Cart',
        index: 'instant_search',
        queryID: results.queryID,
        objectIDs: [hit.objectID]
      })
    "
    > Add to cart </button>

That’s it. You’ve just leaned how to use Angular InstantSearch with Insights.

Google Analytics with Angular InstantSearch

Even though Algolia provides an analytics tailored to your search, you might want to integrate your search into your existing analytics tools. Angular InstantSearch doesn’t provide a built-in widget to implement analytics with other providers.

But you can follow the same strategy that we use for the routing.

Integrating with Google Analytics requires 3 steps:

  • set up the Google Analytics library in your page
  • setup the routing
  • listen within the routing

To set up Google Analytics, the best way is to actually follow the reference guide.

Once the GA library is installed on your website, you can add the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { history as historyRouter } from 'instantsearch.js/es/lib/routers';
import { simple as simpleMapping } from 'instantsearch.js/es/lib/stateMappings';

// use the existing router
const router = historyRouter();
const _write = router.write.bind(router);

// override write
router.write = routeState => {
  _write(routeState);
  const page = router.createURL(routeState);
  // send to Google analytics
  window.ga('send', 'pageView', page);
};

@Component({
  template: `
    <ais-instantsearch
      [config]="{
        appId: 'latency',
        apiKey: '6be0576ff61c053d5f9a3225e2a90f76',
        indexName: 'instant_search',
        routing: routing
      }"
    >
    </ais-instantsearch>
  `,
})
export class AppComponent {
  public routing = { router, stateMapping: simpleMapping() };
}

Here we only send the full URL to Google Analytics but you are free to implement your own function.

Did you find this page helpful?