0
heroes$: Observable<Hero[]>;

 // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
  }
 ngOnInit(): void {
    this.heroes$ = this.searchTerms.pipe(
      // wait 300ms after each keystroke before considering the term
      debounceTime(500),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.searchService.searchHeroes(term)),
    );
  }

  onClear(event){
     console.log('clear observable');
       //clear array
      // I have Tried these two things to clear observable array but it not..
      this.heroes$.map(Hero => Hero = []);
      Observable.of<Hero[]>([]);
  }

I have a Searh box with search suggestion has observable Array.. during onClear event the the Observable Array should Empty.

Mohamed Arshath
  • 423
  • 5
  • 15
  • you can do this, this.heroes$.splice(0) or simply you can do this.heroes$ = [] – PPL Mar 21 '18 at 05:35
  • Property 'splice' does not exist on type 'Observable'. – Mohamed Arshath Mar 21 '18 at 05:39
  • this.heroes$ = [] have following error Type 'undefined[]' is not assignable to type 'Observable'. – Mohamed Arshath Mar 21 '18 at 05:40
  • https://stackoverflow.com/questions/40971285/how-to-return-an-empty-observable/40971371#40971371 – PPL Mar 21 '18 at 05:55
  • Observable.of([]); i Have Tried this but not working.. please help me – Mohamed Arshath Mar 21 '18 at 06:01
  • is there any error? – PPL Mar 21 '18 at 06:02
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167224/discussion-between-ppl-and-mohamed-arshath). – PPL Mar 21 '18 at 06:03
  • Well a) you would need to actually assign `Observable.of([])` to your heroes$ variable for anything to actually happen. b), I believe assigning the variable to a new observable would destroy the old observable and all its subscribers, which probably isn't what you want. Why can't you clear the observable by pushing out a blank search term? Something like this pseudo code ~~ `switchMap((term: string) => { if (term === '') return of([]); else this.searchService.searchHeroes(term)),` – John Mar 21 '18 at 06:06

1 Answers1

1

You could try something like

this.heroes$ = this.searchTerms.pipe(
  // wait 300ms after each keystroke before considering the term
  debounceTime(500),

  // ignore new term if same as previous term
  distinctUntilChanged(),

  // switch to new search observable each time the term changes
  switchMap((term: string) => {
    if (term === '') return Observable.of<Hero[]>([]);
    else return this.searchService.searchHeroes(term);
  }),
);

(so this.heroes$ would emit [] if this.searchTerms emits '')

John
  • 9,249
  • 5
  • 44
  • 76