我正在使用Angular Material“^ 6.4.7”和Angular“^ 6.1.9” . 我做了一些路由来浏览填充了observables的菜单(通过这些observable的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” “或”过滤器“不能与Observables一起使用 .
我不能只过滤Observable的订阅,我需要过滤器返回一个Observable,否则路由将中断 .
有什么建议吗?
1 回答
您调用
map
或filter
等运算符的方式已在Angular 6使用的RxJs 6中发生了变化.Google将为您找到解释所有更改的大量指南,但这将帮助您入门 .您已经以正确的方式使用
switchMap
并且需要继续这样做 .在RxJs 5中,您可以直接调用运算符,如下所示:
等等 .
从RxJs 6开始,你可以管它们 . 所以我上面的伪代码转变为:
完全相同的代码,只需将它们包装在
pipe
调用中 .其他相关更改是从中导入它们的位置 . 所有操作符(可能只是大多数?)都是从
rxjs/operators
导入的,所以要使用map
,switchMap
和filter
,您可以将它包含在文件的顶部:我不确切地知道你想在你的示例代码中做什么,但是你可以在你拥有的内容中添加额外的
pipe
调用: