0

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)
   })
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

that great with your feedback, I kinda a bit confused with your approach, do you mind explaining a bit because I'm getting some errors as I implemented.
I updated the example...and created a stackblitz example angular-j19wsj.stackblitz.io
That's great, very similar to what I wanted but I'm still sorting out to work in my situation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.