【问题标题】:Using rxjs operator is it possible to get second last value使用 rxjs 运算符可以获得倒数第二个值
【发布时间】:2020-04-30 10:48:21
【问题描述】:

这是使用rxjs 运算符的示例代码,我想打印/获取倒数第二个值。

打字稿

import { from } from 'rxjs';
import { map, last } from 'rxjs/operators';

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10)).pipe(last());
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));

目前它打印15,但我希望它打印14

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:
    • takeLast 取最后一个 n 在完成之前发出的值

    • take 将占用第一个 n 号码

    import { from } from "rxjs";
    import { take, takeLast } from "rxjs/operators";
    
    const source = from([1,2,3,4,5]);
    
    source
      .pipe(
        takeLast(2), 
        take(1) 
      )
      .subscribe(console.log);
    

    【讨论】:

      【解决方案2】:

      您可以使用takeLast()skipLast RxJS 运算符。

      takeLast() 运算符允许您

      仅发出源 Observable 发出的最后一个 count 值。

      skipLast() 运算符

      跳过源 Observable 发出的最后一个 count 值。

      现在,我们可以组合两个可管道操作符,这样我们将获取最后 2 个计数,并跳过最后一个计数。

      import { range, from } from 'rxjs';
      import { takeLast, map, skipLast} from 'rxjs/operators';
      
      const source = from([1, 2, 3, 4, 5]);
      
      const example = source
        .pipe(
          map(val => val + 10),
          takeLast(2), 
          skipLast(1)
        );
      
      example.subscribe(res => console.log(res));
      

      这是demo

      【讨论】:

      • 不错的解决方案,它只返回目标值。
      【解决方案3】:

      您可以使用成对运算符:https://www.learnrxjs.io/operators/combination/pairwise.html

      import { from } from 'rxjs';
      import { map,last } from 'rxjs/operators';
      
      //emit (1,2,3,4,5)
      const source = from([1, 2, 3, 4, 5]);
      //add 10 to each value
      const example = source.pipe(map(val => val + 10)).pipe(pairwise(),last());
      //output: 11,12,13,14,15
      const subscribe = example.subscribe(val => console.log(val[0]));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2022-08-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多