gpt4 book ai didi

angular - 根据条件停止 Observable 链的执行

转载 作者:行者123 更新时间:2023-12-02 14:03:22 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com