在 Angular 4 中重置表单控件时总是调用服务 API

always calling the service API when resetting the form control in Angular 4

我下面有一个组件,基本上在 ngOnInit 中调用外部 API 服务 - 这个 returns this.items.

中的 gif 数组

我有函数 applyGif - 一旦用户单击图像,它就会调用此函数并重置表单 searchTerm 问题是每次我调用 resetSearchBox 来清除文本输入框它运行 valueChanges 事件并使用字符串值 'null' 再次执行 gifpickerService.search - 如果它没有值,我不希望它调用它 - 我是什么做错了吗?

我想重置表格但不在 ngOnInit 中调用 search() - 哪里做错了?

export class GifpickerComponent implements OnInit {
   public searchTerm : FormControl = new FormControl();
   public items: any = [];

   @Output() gifSelected: EventEmitter<any> = new EventEmitter<any>();

   constructor(private gifpickerService: GifpickerService) {}

   ngOnInit() {
       this.searchTerm.valueChanges
          .debounceTime(1000)
          .subscribe(data => {
             this.gifpickerService.search(data).subscribe(response =>{
                 this.items = response;
           })

      })
   }

  applyGif(gif): any {
      let gifMedia = gif.media[0];
      this.gifSelected.emit(gifMedia);
      this.resetSearchBox();
  }

  toggleGifList(): void {
      this.items = [];
  }

  resetSearchBox(): void {
      this.searchTerm.reset();
  }
}

/* html 组件 */

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let item of items" [value]="item" class="gif-list-item">
      <img [src]="item.media[0].tinygif.url" (click)="applyGif(item)" />
  </mat-option>
</mat-autocomplete>

当您重置表单控件时,值会更改并因此触发 valueChanges。您可以使用 emitEvent: false 这意味着它不会触发 valueChanges:

resetSearchBox(): void {
  this.searchTerm.reset(null, { emitEvent: false });
}

文档:https://angular.io/api/forms/FormControl#reset