在 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 运算符(以便不执行请求) .
最佳答案
所以,如果我理解正确的话,你想要 .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);
});
关于angular - 根据条件停止 Observable 链的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033789/