以下是一个使用Angular 8和RxJS的示例代码,演示如何从可观察对象中过滤结果:
1.在组件的HTML模板中添加一个输入框和一个显示过滤结果的列表:
- {{ item }}
2.在组件的TypeScript文件中导入必要的模块和服务:
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { FormControl } from '@angular/forms';
3.在组件类中定义一个FormControl和一个Observable数组用于存储过滤结果:
export class AppComponent {
filterText: string;
items: string[] = ['apple', 'banana', 'cherry', 'date'];
filteredItems: Observable;
filterControl = new FormControl();
}
4.在组件的构造函数中使用RxJS的pipe和map操作符创建一个过滤结果的Observable:
constructor() {
this.filteredItems = this.filterControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
}
5.在组件类中添加一个私有方法来过滤结果:
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.items.filter(item => item.toLowerCase().includes(filterValue));
}
这样,当用户在输入框中输入文本时,列表将根据输入内容动态过滤显示结果。