|
1 | 1 | 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'; |
2 | 12 |
|
3 | 13 | @Component({ |
4 | 14 | selector: 'app-product', |
5 | 15 | standalone: true, |
6 | | - imports: [], |
| 16 | + imports: [NgIf, NgFor, RouterLink], |
7 | 17 | templateUrl: './product.component.html', |
8 | 18 | }) |
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