• RxJS之过滤操作符 ( Angular环境 )


    一 take操作符

    只发出源 Observable 最初发出的的N个值 (N = count)。 如果源发出值的数量小于 count 的话,那么它的所有值都将发出。然后它便完成,无论源 Observable 是否完成。

    import { Component, OnInit } from '@angular/core';
    import { range } from 'rxjs/observable/range';
    import { take } from 'rxjs/operators/take';
    
    @Component({
      selector: 'app-filter',
      templateUrl: './filter.component.html',
      styleUrls: ['./filter.component.css']
    })
    export class FilterComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        range(100, 10)
          .pipe(take(5))
          .subscribe(val => {
            console.log(val);
          });
      }
    
    }

     二 distinctUntilChanged操作符

    返回 Observable,它只发出源 Observable 发出的与前一项不相同的项。

     如果没有提供 compare 函数,默认使用===严格相等检查。

    import { Component, OnInit } from '@angular/core';
    import { of } from 'rxjs/observable/of';
    import { distinctUntilChanged } from 'rxjs/operators/distinctUntilChanged';
    
    @Component({
      selector: 'app-filter',
      templateUrl: './filter.component.html',
      styleUrls: ['./filter.component.css']
    })
    export class FilterComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        of(1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3)
          .pipe(distinctUntilChanged())
          .subscribe(
            val => {
              console.log(val);
            }
          );
      }
    
    }

    如果提供了 compare 函数,那么每一项都会调用它来检验是否应该发出这个值。

    import { Component, OnInit } from '@angular/core';
    import { of } from 'rxjs/observable/of';
    import { distinctUntilChanged } from 'rxjs/operators/distinctUntilChanged';
    
    export class Person {
      constructor(public name: string, public age: number) { }
    }
    
    @Component({
      selector: 'app-filter',
      templateUrl: './filter.component.html',
      styleUrls: ['./filter.component.css']
    })
    export class FilterComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        of<Person>(
          new Person('Leo', 11),
          new Person('Raph', 12),
          new Person('Mikey', 13),
          new Person('Mikey', 14)
        )
          .pipe(
            // of方法使用了泛型,可以省略指定p、q为Person类型
            distinctUntilChanged((p, q) => p.name === q.name)
          )
          .subscribe(
            val => {
              console.log(val);
            }
          );
      }
    
    }

  • 相关阅读:
    删除数据库的数据后让id从1开始算
    通过数据库绑定的dropdownlist,如何让其第一条默认显示"--请选择--"
    winform 验证用户正确后打开新窗口时关闭登陆窗口
    winform FormBordStyle=none 及 wpf FormBordStyle=none 的鼠标点击移动问题
    [AngularJS] AngularJS系列(3) 中级篇之表单验证
    linux开启mysql远程登录
    linux下JDK,tomcat的安装与环境变量配置
    linux下mysql连接jar包的位置在哪里?
    linux下mysql忘记root密码的解决方案
    RedHat下MySQL 5.6 安装、维护
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/8969237.html
Copyright © 2020-2023  润新知