【问题标题】:Angular - Async Pipe and SearchAngular - 异步管道和搜索
【发布时间】:2019-04-07 16:17:31
【问题描述】:

我知道这是完全错误的......但是我找不到一个例子来实现它

search = '';
ngOnInit() {
    this.countries$ = this.areasService.getCountries(this.search); //HttpClient request
}

search(key) {
    this.search = key;
    this.countries$.next();
}

<ul>
    <li *ngFor="let c of (countries$ | async)?.docs">{{c.name}}</li>
</ul>

【问题讨论】:

  • 你想完成什么?
  • 我有一个国家列表和一个按名称搜索的输入
  • 所以您想在每次搜索更改时调用获取国家/地区功能?
  • 是的.....我认为 this.countries$.next();是正确的......但下一个不是函数是错误
  • Next 是一个供观察者使用的函数,如果你愿意的话,你可以做一个 switchmap 并在里面创建一个你调用 next 的主题,但我认为这基本上是下面给出的答案。

标签: angular observable angular-httpclient angular-pipe angular-observable


【解决方案1】:

为了能够订阅和发布到 observable,您可以使用 Subject。

考虑到这一点,您可以触发您的 http 调用,并将新值广播给您的主题。

search = '';
countries$ = new Subject();
ngOnInit() {
    this.refreshCountries();
}

search(key) {
    this.search = key;
    this.refreshCountries();
}

refreshCountries(){
    this.areasService.getCountries(this.search)
       .subscribe((value) => {
         if(value && value.docs){
            console.log('received docs =', value.docs);
            this.countries$.next(value.docs)); //HttpClient request
         }
}

<ul>
    <li *ngFor="let c of (countries$ | async)">{{c.name}}</li>
</ul>

注意:为了减少你发出的请求数量(这是你很快会遇到的问题),你可以使用 debounceTime

【讨论】:

  • 与“this.countries$ = this.areasService.getCountries(this.search);”有什么区别
  • this.countries$ = this.areasService.getCountries(this.search);是一个任务,你改变 his.countries$ 的性质,我写的就是广播,你在里面发出一个新的值。
  • @Michalis 本质上,是的。因为这就是你所做的:进行 http 调用并将新值发布到观察者中。您可以将命令重构为您调用两次的函数,但从根本上说,您最终会做同样的事情。
  • 我尝试了代码......它执行新请求......但它不会改变异步管道
  • @Michalis 你能发布触发“搜索”的代码吗?另外,您能否检查 areaService 是否在每次搜索时触发?
猜你喜欢
  • 1970-01-01
  • 2020-10-08
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
相关资源
最近更新 更多