Yeysides
Yeysides

Reputation: 1292

Nesting subscribe within formControl.valuesChange

I have a subscription on the changing value of an input formControl and I need to take those values as the user types to make another call. This works but it feels wrong since I thought the point of observables was to rid callback hell. Any help?

  constructor(private symbolSearchService: SymbolSearchService) {
    this.symbolSearchForm = new FormControl();
  }

  ngOnInit() {
    this.symbolSearchForm.valueChanges.subscribe(
      val => {
        this.symbolSearchService.symbolLookup(val).subscribe(
          val => console.log('val', val)
        )
      }
    )
  }

Upvotes: 0

Views: 389

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122061

You can flatten this out using the observable operators:

this.symbolSearchForm.valueChanges
  .mergeMap(val => this.symbolSearchService.symbolLookup(val))
  .subscribe(val => console.log('val', val));

See e.g. https://www.learnrxjs.io/operators/transformation/mergemap.html

Upvotes: 1

Related Questions