zoukankan      html  css  js  c++  java
  • 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);
            }
          );
      }
    
    }

  • 相关阅读:
    SCP测试服务器的上行/下行带宽
    React-Native 之 GD (四)使用通知方式隐藏或显示TabBar
    React-Native 之 GD (五)属性声明和属性确认 及 占位图
    React-Native 之 GD (三)近半小时热门
    React-Native 之 GD (二)自定义共用导航栏样式
    React-Native 之 GD (一)目录结构与第三方框架使用与主题框架搭建
    React Native商城项目实战16
    React Native商城项目实战15
    React Native商城项目实战14
    React Native商城项目实战13
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/8969237.html
Copyright © 2011-2022 走看看