【问题标题】:Stop the execution of an Observable chain based on a condition根据条件停止 Observable 链的执行
【发布时间】:2017-06-21 09:18:52
【问题描述】:

在一个 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..."/>

如果 formControl 发出的值是 null .

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案1】:

    因此,如果我理解正确,如果它们为空,您希望 .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); 
      });
    

    【讨论】:

    • 如果过滤器阻塞了链的其余部分,你仍然想返回一个值,即使是 null 怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    • 2019-03-21
    • 2016-02-26
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多