加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 多个可观察的一起工作

发布时间:2020-12-17 17:00:28 所属栏目:安全 来源:网络整理
导读:我有一个输入,当用户键入它时,它执行实时搜索.例如,假设他搜索了以下内容: car 结果将是: [ { id: "1" name: "Ferrari" },{ id: "2" name: "Porsche" }] 这个我能够成功,这是如何: class WordComponent { word: Subjectstring = new Subjectstring(); res
我有一个输入,当用户键入它时,它执行实时搜索.例如,假设他搜索了以下内容:

car

结果将是:

[
  {
    id: "1"
    name: "Ferrari"
  },{
    id: "2"
    name: "Porsche"
  }
]

这个我能够成功,这是如何:

class WordComponent {
  word: Subject<string> = new Subject<string>();
  result: any[] = [];

  constructor(private http: Http) {
    this.subscribe();
  }

  subscribe(): void {
    this.word.debounceTime(400)
      .distinctUntilChanged()
      .switchMap((word: string): Observable<any[]> => this.http.get(word))
      .subscribe((result: any[]): any[] => this.result = result);
  }

  search(event: any): void {
    this.word.next(event.target.value);
  }

}

并且观点:

<input type="text" placeholder="Word" (keyup)="search($event)">

我希望用户能够同时键入多个单词并分别对每个单词进行实时搜索.例如,假设他搜索了以下内容:

car food sun

汽车的结果将是:

[
  {
    id: "1"
    name: "Ferrari"
  },{
    id: "2"
    name: "Porsche"
  }
]

食物的结果将是:

[
  {
    id: "3"
    name: "egg"
  },{
    id: "4"
    name: "cheese"
  }
]

太阳的结果将是:

[
  {
    id: "5"
    name: "star"
  },{
    id: "6"
    name: "sky"
  }
]

并且还合并每个单词的结果,在这种情况下它看起来像这样:

[
  [{
      id: "1"
      name: "Ferrari"
    },{
      id: "2"
      name: "Porsche"
    }
  ],[{
      id: "3"
      name: "egg"
    },{
      id: "4"
      name: "cheese"
    }
  ],[{
      id: "5"
      name: "star"
    },{
      id: "6"
      name: "sky"
    }
  ]
]

但是,让我们说用户在输入所有单词并执行搜索后,希望更改其中一个.只需要重新搜索已更改的单词,并且必须重做最终结果的合并.

我仍然不知道rxjs的所有功能,我不知道实现这一目标的理想方法是什么.如果你想要一个参考,Display Purposes网站有一个非常相似的搜索引擎.

解决方法

我想你需要这样的东西:

subscribe(): void {
  this.word.debounceTime(400)
  .distinctUntilChanged()
  .switchMap((words: string): Observable<any[]> => 
    Observable.forkJoin(words.split(' ').map(word => this.http.get(word))) 
  )
  .map(arrayWithArrays => [].concat(arrayWithArrays)
  .subscribe((result: any[]): any[] => this.result = result);
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读