根据条件停止执行Observable链

Nac*_*ene 3 observable rxjs angular

在Angular应用程序中,我的组件中有这个Observable链:

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

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); });
Run Code Online (Sandbox Code Playgroud)

}}

seach.ccomponent.html

<input [formControl]='queryField' type="text" id="keyword" autocomplete="off" placeholder="start typing..."/>
Run Code Online (Sandbox Code Playgroud)

我想要做的是取消执行其余的Observables链,如果formControl发出的值为null,则不要转到switchMap操作符(为了不执行请求).

Mar*_*ten 7

所以,如果我理解正确,你想要.filter()排放,如果它们为null,那么你的switchMap不会被执行:

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); 
  });
Run Code Online (Sandbox Code Playgroud)

  • 我很困惑.你有超过5000个声望点并发表评论作为答案?! (4认同)