Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop the execution of an Observable chain based on a condition

In an Angular application, I have this Observable chain in my component :

@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

search.component.ts

results: any[] = [];
queryField: FormControl = new FormControl();
constructor(private _apiService: ApiService) { }

ngOnInit() {

this.queryField.valueChanges
.debounceTime(200)
.distinctUntilChanged()
.switchMap((query) => this._apiService.search(query)) // was subscribe
.subscribe(result => {  this.results = result.items; console.log(result); });

} }

seach.ccomponent.html

<input [formControl]='queryField' type="text" id="keyword" autocomplete="off" placeholder="start typing..."/>

What I would like to do is to cancel the execution of the rest of the Observables chain and don't go to the switchMap operator (in order to don't execute the request) if the value emitted du the formControl is null.

like image 834
Nacim Idjakirene Avatar asked Feb 03 '17 22:02

Nacim Idjakirene


1 Answers

So if I understand correctly you want to .filter() emissions if they are null so your switchMap is not executed:

this.queryField.valueChanges
  .filter((q) => q !== null) // only proceed if the value is not null
  .debounceTime(200)
  .distinctUntilChanged()
  .switchMap((query) => this._apiService.search(query)) // was subscribe
  .subscribe(result => {  
    this.results = result.items; 
    console.log(result); 
  });
like image 69
Mark van Straten Avatar answered Oct 12 '22 23:10

Mark van Straten