【问题标题】:Run switchmap operator when calling next - Angular 7调用下一个时运行 switchmap 运算符 - Angular 7
【发布时间】:2019-06-06 06:19:40
【问题描述】:

我使用主题和 async 管道发出 http 请求并根据搜索词进行搜索。我使用角度教程来执行此操作,该教程使用 switchmap 运算符和 keyup 方法的一些延迟时间。

击键工作正常,但我第一次想发出请求调用并显示列表,然后用户可以根据需要进行搜索。

但在调用 next 时,switchmap 运算符不会触发!

搜索输入:

<input type="text" placeholder="Search name" [(ngModel)]="searchTerm" (keyup)="callSearch()">

打字稿代码:

 products$: Observable<ProdSearch[]>;
 searchProducts$ = new Subject<string>();
 callSearch() {
   if (this.searchTerm.length > 0 ){
    this.searchProducts$.next(this.searchTerm);
   }
 }

订阅:

this.products$ = this.searchProducts$.pipe(
  debounceTime(1000),
  distinctUntilChanged(),
  switchMap(term => {
    const options: PagingOptions = {};
    options.limit = "5";
    if (term.length !== 0) {
      options.filterOptions = "name_search_" + this.searchTerm;
    }

    return this.service.getCollection<ProdSearch>(this.baseUrl + 'products/search', options)
      .pipe(map(collection => collection.records))
  })

我想第一次使用按钮运行 switchmap,但它不起作用,它只适用于击键。

showLastProducts() {
this.showChangeList = true;
this.searchProducts$.next(''); // The switchmap won't work
}

【问题讨论】:

  • 尝试使用BehaviorSubject 而不是Subject,或使用startWith 运算符。问题是主题不会发出第一个值,因此您必须手动完成,或者使用他们的小兄弟,即行为一。
  • ... 或添加startWith 运算符

标签: angular rxjs angular6 observable angular7


【解决方案1】:

尝试切换:

searchProducts$ = new Subject<string>();

到这里:

searchProducts$ = new BehaviorSubject<string>('');

这将在您输入任何内容之前发出一个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 2022-08-19
    • 2018-07-28
    • 2020-05-12
    相关资源
    最近更新 更多