-1

In the following search method, I just set the BehaviourSubject value in the service. So, I am not sure if I can perform this without using subscribe() or toPromise() after .pipe() block in the following method. But if not, which one should I use? And, assuming that there is no validation for the search input, should I get the response or subscribe to the result of setting this value?

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);
    });
}
Jack
  • 1
  • 21
  • 118
  • 236

1 Answers1

1

That depends on you.

Subscribing (using Observables) are preferred if you want to do more than just 1 action and they are cancelable.

Promises handle only a single event.

See: Difference of Observables and Promises

Personally, I use promises if its something that is simple such as fetching data and catching any errors then displaying the error messages.

  • Ok thanks for reply. As I said, I had already read the differences, but I confused this particular situation. So, I think I have to use one of them after `pipe()` block and there is not other option to call the service method in this method? Any idea? – Jack Nov 02 '20 at 17:20
  • Any idea regarding to my last comment? – Jack Nov 02 '20 at 17:28
  • I think you should subscribe, its less code and it gets the job done. – John Michael Manlupig Nov 02 '20 at 17:56
  • I tried both of them again, and see that when using promise, it waits the result. So, I should use subscribe and there is not other option. Thanks. – Jack Nov 02 '20 at 18:08