使用 mergeMap 时智能搜索不起作用

Smart search is not working when working with mergeMap

我想在 angular

中使用智能搜索
<input type="text" [formControl]="leadForm" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
   <mat-option *ngFor="let item of results" [value]="item">
   {{item}}
   </mat-option>
</mat-autocomplete>

leadForm = new FormControl(null, Validators.required);

然后在ngOnInit()

 combineLatest([s1,s2,s3])
 .pipe(
 mergeMap(([r1, r2, r3]) => {
     this.x = r1;
     this.y = r2;
     this.names = r3;
     return of(1);
 }))
 .subscribe(() => {
     // display
 });
 this.leadForm.valuesChanges.subscribe(
     r => {
       if(r !== '') {
           this.results = this.names.filter(c => c.toLowerCase().includes(item.toLowerCase()));
       }
    }
 );

所以我的想法是从数据流中获取名称,然后填充下拉列表。但是有时它不起作用。我猜流顺序是错误的。我们需要先得到this.names。如何修改密码?

很高兴知道 s1 -- s3 是什么..

但总的来说,您应该重构它,以便结果是一个可观察的依赖于 leadForm.valueChanges。

类似于:

this.results$ = this.leadForm.valueChanges.pipe(map(...));

你的问题是你订阅了 2 个 observables 并期望顺序被定义,但是两者都可能有这些情况:它永远不会解决,其中一个首先解决(分别是最后一个),有一个错误。为了给你更多的建议,我需要更多地了解这个案例。:/

听起来您需要一种更具反应性的方法,您可以在其中为 Observable 声明变量并对这些变量的变化做出反应。

没有确切的代码,很难为您找到一个确切的例子,但像这样:

names$ = this.http.get(...);

leadForm$ = this.leadForm.valueChanges();

results$ = combineLatest([names$, leadForm$]).pipe(
     map(([names, r]) => names.filter(c => c.toLowerCase().includes(r.toLowerCase()))
);

这应该会让你接近。

然后您可以在某处订阅 results$ 或使用异步管道直接绑定到它。

我这里有一个这种技术的例子:https://www.youtube.com/watch?v=0EefbG6N3vY

如果您有 Pluralsight 订阅,这里有一个完整的演练:https://app.pluralsight.com/course-player?clipId=5732473c-ac12-450d-930c-096a687dd2d0