I am developing an Angular4 Application with Azure Search. I need to make a call to get products according to a search string. the HTML is:
<input name="searchQuery" class="form-control" id="" [(ngModel)]="query">
<button class="btn btn-default" type="submit" [routerLink]="['/search', query]" (click)="search()">Suchen</button>
the search component:
export class SearchResultQueryComponent implements OnInit {
public query: string;
private products: Product[];
@Output() searchEvent: EventEmitter<Product[]> = new EventEmitter();
private searchTerms = new Subject<string>();
constructor(private route: ActivatedRoute,) {
this.products = [];
}
ngOnInit() {
this.route.params.subscribe(params => {
this.query = params.query;
});
}
search() {
if (this.query != null && this.query !== '' && this.query.length !== 0) {
this.searchTerms.next(this.query);
this.azureSearchApiService.search(this.searchTerms, ['brand'], 0)
.subscribe(p => {
this.products = p.value;
});
this.searchEvent.emit(this.products);
} else {
return;
}
}
}
the parent component:
searchResult(products: Product[]) {
if (this.products != null) {
this.products = products;
}
}
the search service:
headers = new Headers();
constructor(private http: Http, private translate: TranslateService) {
this.headers.append('Content-Type', 'application/json');
this.headers.append('api-key', '73E96D367A256255E88DA72931E4CD72');
}
search(terms: Observable<string>, facets: string[], page: number) {
return terms
.distinctUntilChanged()
.switchMap(term => this.searchEntries(term, facets, page) );
}
searchEntries(term, facets: string[], page: number) {
const requestOptions = new RequestOptions({ headers: this.headers });
const searchOptions = this.searchOptions(term, facets, page);
return this.http
.post('the url....', searchOptions, requestOptions)
.map(res => res.json())
}
searchOptions(searchTerm: string, facets: string[], page: number): any {
const options = {
search: '*' + searchTerm,
facets: [ facets.join(',')],
// paging
top: 5,
skip: 5 * page,
count: true,
};
return JSON.stringify(options);
}
The problem is: I always receive the same result which is all, although the search term is right. and the second problem is that I have to click the button three times to receive the results. I cannot understand why? and what to do?
any idea could be helpful. thank you