如何在 Angular Material 自动完成中过滤用于路由的可观察对象

How to filter observables for routing in Angular Material Autocomplete

我正在使用 Angular Material“^6.4.7”和 Angular“^6.1.9”。 我完成了一些路由以在充满可观察对象的菜单中导航(通过这些可观察对象的 id 进行导航)。现在我必须添加一个自动完成功能来过滤此菜单(以帮助用户找到特定选项),但我在实现这一点时遇到了一些麻烦。

我的html

    <mat-form-field>
        <mat-label>Find datasource...</mat-label>
        <input matInput name="datasource filter" [formControl]="searchForm" [ngModel]="dataSourceFilterInput">
    </mat-form-field>

    <div *ngFor="let datasource of dataSourceFiltered$ | async">
        <div [routerLink]="[datasource.id]">
            <h6>{{datasource.name}}</h6>
        </div>
    </div>

我的学生:

export class DataSourceSelectorComponent implements OnInit {

dataSourceFiltered$: Observable<IDataSourceDefinition[]>;
dataSource$: Observable<IDataSourceDefinition[]>;
dataSourceList: IDataSourceDefinition[] = [];
searchForm: FormControl = new FormControl();

constructor(private _datasourceService: DataSourceConfigurationService, private _route: ActivatedRoute) {
}

ngOnInit() {
    this.dataSourceFiltered$ = this._route.paramMap.pipe(
        switchMap(params => {
            this.selectedId = +params.get("id");
            this.dataSource$ = this._datasourceService.getAllDataSources();
            this.dataSource$.subscribe(ds => (this.dataSourceList = ds));
            return this.dataSource$;
        })
    );
}

}

其中 IDataSourceDefinition 是我与 属性 "name" 的接口。

我认为我必须在 ngOnInit 中添加过滤器(如 Angular Material 中所建议的使用表单控件(在本例中为 searchForm)和 "valueChanges.pipe()"),但是所有方法都像"map" 或 "startWith" 或 "filter" 不能与 Observables 一起使用。

我不能只过滤 Observable 的订阅,我需要过滤 returns Observable,否则路由会中断。

有什么建议吗?

你调用像 mapfilter 这样的运算符的方式在 RxJs 6 中发生了变化,它被 Angular 6 使用。Google 会为你找到很多指南这将解释所有更改,但这将帮助您入门。

您已经 switchMap 以正确的方式使用,需要继续这样做。

在 RxJs 5 中,您可以直接调用运算符,如下所示:

someObservable
  .map(item => doSomethingWith(item))
  .filter(item => isThisItemValid(item));

以此类推

从 RxJs 6 开始,您可以将它们全部通过管道传输。所以我上面的伪代码变成了:

someObservable
  .pipe(map(item => doSomethingWith(item)))
  .pipe(filter(item => isThisItemValid(item)));

完全相同的代码,只是将它们包装在 pipe 个调用中。

另一个相关的变化是你从哪里导入它们。所有运算符(也许只是大多数?)都是从 rxjs/operators 导入的,因此要使用 mapswitchMapfilter,您需要将其包含在文件顶部:

import { map, switchMap, filter } from 'rxjs/operators';

我不确切知道您想在示例代码中做什么,但您可以在现有代码的末尾添加额外的 pipe 调用:

ngOnInit() {
    this.dataSourceFiltered$ = this._route.paramMap.pipe(
        switchMap(params => {
            this.selectedId = +params.get("id");
            this.dataSource$ = this._datasourceService.getAllDataSources();
            this.dataSource$.subscribe(ds => (this.dataSourceList = ds));
            return this.dataSource$;
        })
    )
    .pipe(filter(item => filterItHere(item)))
    .pipe(map(item => mapItHere(item)));
}