• filter
    • 签名: filter(select: Function, thisArg: any): Observable
  • 发出符合给定条件的值。
    • 示例
      • 示例 1: 过滤出偶数
      • 示例 2: 基于属性过滤对象
      • 示例 3: 过滤出大于给定值的数字
  • 相关食谱
  • 其他资源

    filter

    签名: filter(select: Function, thisArg: any): Observable

    发出符合给定条件的值。


    :bulb: 如果你希望当不满足条件时完成 observable 的话,请查阅 takeWhile!


    示例

    示例 1: 过滤出偶数

    ( jsBin |
    jsFiddle )

    1. import { from } from 'rxjs/observable/from';
    2. import { filter } from 'rxjs/operators';
    3. // 发出 (1,2,3,4,5)
    4. const source = from([1, 2, 3, 4, 5]);
    5. // 过滤掉奇数
    6. const example = source.pipe(filter(num => num % 2 === 0));
    7. // 输出: "Even number: 2", "Even number: 4"
    8. const subscribe = example.subscribe(val => console.log(`Even number: ${val}`));
    示例 2: 基于属性过滤对象

    ( jsBin |
    jsFiddle )

    1. import { from } from 'rxjs/observable/from';
    2. import { filter } from 'rxjs/operators';
    3. // 发出 ({name: 'Joe', age: 31}, {name: 'Bob', age:25})
    4. const source = from([{ name: 'Joe', age: 31 }, { name: 'Bob', age: 25 }]);
    5. // 过滤掉年龄小于30岁的人
    6. const example = source.pipe(filter(person => person.age >= 30));
    7. // 输出: "Over 30: Joe"
    8. const subscribe = example.subscribe(val => console.log(`Over 30: ${val.name}`));
    示例 3: 过滤出大于给定值的数字

    ( jsBin |
    jsFiddle )

    1. import { interval } from 'rxjs/observable/interval';
    2. import { filter } from 'rxjs/operators';
    3. // 每1秒发出值
    4. const source = interval(1000);
    5. // 过滤掉所有值知道 interval 发出的值大于5
    6. const example = source.pipe(filter(num => num > 5));
    7. /*
    8. "Number greater than 5: 6"
    9. "Number greater than 5: 7"
    10. "Number greater than 5: 8"
    11. "Number greater than 5: 9"
    12. */
    13. const subscribe = example.subscribe(val =>
    14. console.log(`Number greater than 5: ${val}`)
    15. );

    相关食谱

    • 游戏循环

    其他资源

    • filter :newspaper: - 官方文档
    • 使用 filter 添加条件逻辑 :video_camera: :dollar: - John Linquist
    • 过滤操作符: filter :video_camera: :dollar: - André Staltz

    :file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/filter.ts