Last active
November 1, 2019 18:16
-
-
Save jrodl3r/a4a4cd23328aa66abb454ebe39116471 to your computer and use it in GitHub Desktop.
ElasticSearch - Angular Search Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class SearchService { | |
data: any; | |
results: IContact[]; | |
isFetching = false; | |
constructor(private functions: AngularFireFunctions) { } | |
public getResults(query: string) { | |
const call = this.functions.httpsCallable('searchContacts'); | |
this.isFetching = true; | |
call({ query }).subscribe( | |
response => { | |
if (response) { | |
this.data = response; | |
if (this.data.hits && this.data.hits.hits.length) { | |
this.results = []; | |
this.data.hits.hits.forEach((item, index) => this.results[index] = item._source); | |
this.results = this.results.slice(0, 5); // Shrink to 5 items | |
} else { | |
this.reset(); | |
} | |
} | |
this.isFetching = false; | |
}, | |
error => { | |
console.error(`Error fetching search results`, error); | |
this.isFetching = false; | |
} | |
); | |
} | |
public reset() { | |
this.data = {}; | |
this.results = []; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment