Angular - 单击时清除 Observable

Loz*_*e15 2 observable rxjs angular

基于 angular.io 英雄教程教程中的搜索,我使用 observable 创建了一个简单的动物搜索。一切正常,但是我现在想清除搜索中的值,并在选择结果时清除结果列表。

我创建了一个方法来清除单击链接时的输入值,期望 observable 会更新和清除,不幸的是这并没有发生,并且下拉列表仍然存在。我试过重新分配 observable,这是可行的,但随后 observable 被取消订阅,这是我不想做的事情。

我确定这是我还没有完全理解如何使用 observables 的一个例子,所以希望你们能帮助我。

谢谢,这是我的代码。

import { Component, OnInit } from '@angular/core';

import {Observable, Subject} from 'rxjs'

import {
  debounceTime, distinctUntilChanged, switchMap
} from 'rxjs/operators';

import { AnimalService } from '../services/animal.service';
import { Animal } from '../models/animal';

@Component({
  selector: 'app-animal-search',
  templateUrl: './animal-search.component.html',
  styleUrls: ['./animal-search.component.css']
})
export class AnimalSearchComponent implements OnInit {
  animals$: Observable<Animal[]>;
  private searchTerms = new Subject<string>();
  private searchTerm: string;

  constructor(private animalService: AnimalService) { }

  search(term: string):void {
    this.searchTerms.next(term);
  }

  ngOnInit() {
    this.animals$ = this.searchTerms.pipe(

      debounceTime(300),

      distinctUntilChanged(),

      switchMap((term: string) => this.animalService.searchAnimals(term)),
    );

    this.animals$.subscribe( )
  }

  clearSearch()
  {
    //PART THAT ISNT WORKING
    this.searchTerm = "";
    this.searchTerms = new Subject<string>();
  }

}
Run Code Online (Sandbox Code Playgroud)
<div id="search-component" class="search-component-container">
  <input #searchBox id="search-box" [(ngModel)]="searchTerm"  (keyup)="search(searchBox.value)" class="search-component-input" />

  <ul class="search-result">
    <li *ngFor="let animal of animals$ | async" >
      <a routerLink="/animal/{{animal.id}}" (click)="clearSearch()"> 
        {{animal.Name}}
      </a>
    </li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

pei*_*ent 5

不确定您想要达到的确切目标,但是根据您的问题,您似乎想要执行以下操作:

clearSearch()
{
  this.searchTerms.next('');
}
Run Code Online (Sandbox Code Playgroud)

根据您想要的结果,您也可以执行以下操作:

  initAnimals() {
    if (this.animals$) {
      this.animals.unsubscribe();
    }

    this.animals$ = this.searchTerms.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((term: string) => this.animalService.searchAnimals(term)),
    );

    this.animals$.subscribe( )
  }

  ngOnInit() {
    this.initAnimals();
  }

  clearSearch() {
    this.initAnimals();
  }
Run Code Online (Sandbox Code Playgroud)