Reputation: 27
I'm learning how to use Angular with an API and I have a search box where I can search for a data, now I want to make multiple searches as in if I make a search and get the result and clear and type different keyword I still get a result but I don't seem to get any after.
app.component.html
<input id="search" type="text" placeholder="" [(ngModel)]="inputKeyword" name="search" />
app.component.ts
searchData() {
this.results = this.googleService.getGoogle(this.inputKeyword)
.subscribe(x =>{
this.googleData = x.items;
console.log('googleData', this.googleData);
}, error => {
console.log("error here",error)
})
}
Upvotes: 0
Views: 1864
Reputation: 607
Try something like this.. Assuming latest version(s) of Angular.
Here is a stackbliz example: https://angular-j19wsj.stackblitz.io
in the app.component.html
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
Enter search value:
<input type="text" name="search" (keyup)="search($event)">
<br>
<ng-container *ngIf="(data$ | async) as data">
<ul>
<li *ngFor="let x of data">{{x}}</li>
</ul>
</ng-container>
Then in app.component.ts
import { Component } from '@angular/core';
import { Subject, Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
searchValue$ = new Subject<string>();
data$: Observable<string[]>;
testData = [
'mike',
'john',
'john doe',
'susan',
'susie'
]
constructor(){
this.searchValue$.pipe(
switchMap(sv=>{
//reeturn apiservice.get(searchvalue);
console.log('sv is' ,sv)
return of(this.testData.filter(x=>x.startsWith(sv)));
})
).subscribe(result=>{
this.data$ = of(result);
})
}
search(e:KeyboardEvent){
this.searchValue$.next(e.target.value);
}
}
And then you can throw in some debounce to prevent from being called too much
Upvotes: 1