Skip to content

Commit eb56a07

Browse files
committed
feat(angular): PDP with recommend
1 parent f2ab145 commit eb56a07

2 files changed

Lines changed: 81 additions & 3 deletions

File tree

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,15 @@
1-
<p>product works!</p>
1+
<div *ngIf="hit">
2+
<a routerLink="/">Back</a>
3+
<h1>{{ hit.name }}</h1>
4+
<p>{{ hit.description }}</p>
5+
<p>$ {{ hit.price }}</p>
6+
7+
<h2>Related Products</h2>
8+
<ul>
9+
<li *ngFor="let item of relatedItems">
10+
<a routerLink="/product" [queryParams]="{ objectID: item.objectID }">
11+
{{ item.name }}
12+
</a>
13+
</li>
14+
</ul>
15+
</div>
Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,73 @@
11
import { Component } from '@angular/core';
2+
import {
3+
connectConfigure,
4+
connectHits,
5+
connectRelatedProducts,
6+
} from 'instantsearch.js/es/connectors';
7+
import { PlainSearchParameters } from 'algoliasearch-helper';
8+
import { InstantSearchService } from '../instant-search.service';
9+
import { Hit, Widget } from 'instantsearch.js';
10+
import { ActivatedRoute, RouterLink } from '@angular/router';
11+
import { NgFor, NgIf } from '@angular/common';
212

313
@Component({
414
selector: 'app-product',
515
standalone: true,
6-
imports: [],
16+
imports: [NgIf, NgFor, RouterLink],
717
templateUrl: './product.component.html',
818
})
9-
export class ProductComponent {}
19+
export class ProductComponent {
20+
hit?: Hit;
21+
relatedItems?: Hit[];
22+
refine?: (searchParameters: PlainSearchParameters) => void;
23+
widgets: Array<Widget> = [];
24+
objectID?: string;
25+
26+
constructor(
27+
private route: ActivatedRoute,
28+
private InstantSearchService: InstantSearchService
29+
) {
30+
const objectID = route.snapshot.queryParamMap.get('objectID');
31+
if (!objectID) {
32+
throw new Error('objectID is required');
33+
}
34+
35+
this.replaceWidgets(objectID);
36+
}
37+
38+
replaceWidgets(objectID: string) {
39+
if (this.objectID === objectID) {
40+
return;
41+
}
42+
this.objectID = objectID;
43+
this.InstantSearchService.removeWidgets(this.widgets);
44+
this.widgets = [
45+
connectConfigure(() => {})({
46+
searchParameters: {
47+
filters: `objectID:${objectID}`,
48+
} as PlainSearchParameters,
49+
}),
50+
connectHits(({ items }) => {
51+
this.hit = items[0];
52+
})({}),
53+
connectRelatedProducts(({ items }) => {
54+
this.relatedItems = items;
55+
})({ objectIDs: [objectID] }),
56+
];
57+
this.InstantSearchService.addWidgets(this.widgets);
58+
}
59+
60+
ngOnInit() {
61+
this.route.queryParams.subscribe((params) => {
62+
this.replaceWidgets(params.objectID);
63+
});
64+
}
65+
66+
ngAfterContentInit() {
67+
this.InstantSearchService.start();
68+
}
69+
70+
ngOnDestroy() {
71+
this.InstantSearchService.dispose();
72+
}
73+
}

0 commit comments

Comments
 (0)