在Angular应用程序中,我的组件中有这个Observable链:
@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..."/>
我想要做的是取消执行其余的Observables链,如果formControl发出的值为null,则不要转到switchMap运算符(为了不执行请求)
答案 0 :(得分:6)
因此,如果我理解正确,您希望.filter()
排放如果它们为空,那么您的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);
});