我应该使用 subecribe 还是 toPromise 来调用服务方法?

Should I use subecribe or toPromise for just calling a service method?

在下面的搜索方法中,我只是在服务中设置了BehaviourSubject值。因此,我不确定在以下方法中 .pipe() 块之后是否可以在不使用 subscribe()toPromise() 的情况下执行此操作。但如果不是,我应该使用哪一个?而且,假设搜索输入没有验证,我应该得到响应还是订阅设置这个值的结果?

search() {
    fromEvent(this.searchInput.nativeElement, 'keyup').pipe(

      // get value
      map((event: any) => {
        return event.target.value;
      }),
      debounceTime(1000),      
      distinctUntilChanged()
    )

    // subscribe ?
    .subscribe(x => {
      this.searchService.setSubject(x);
    });

    // toPromise ?
    .toPromise().then(x => {
      this.searchService.setSubject(x);
    });
}

这取决于你。

如果你想做的不仅仅是 1 个动作并且它们是可取消的,那么订阅(使用 Observables)是首选。

Promises 只处理一个事件。

参见:

就我个人而言,我使用 promises 如果它是简单的东西,例如获取数据和捕获任何错误,然后显示错误消息。