使用RXJS last()从数组中获取最后一个数据

使用RXJS last()从数组中获取最后一个数据,rxjs,Rxjs,我在使用RXJS方法获取所需内容时遇到问题 this.tutorials$ .pipe( map( data => data.map(item => item.id)), // returns [10,20,30,40] last() ) .subscribe( console.log ); // returns nothing. Isn't supposed to return 40? 我想提取数组的最后一项。我做错了什么?除了最后一种方法,还有更好的

我在使用RXJS方法获取所需内容时遇到问题

this.tutorials$
  .pipe(
    map( data => data.map(item => item.id)), // returns [10,20,30,40]
    last()
  )
  .subscribe( console.log ); // returns nothing. Isn't supposed to return 40?
我想提取数组的最后一项。我做错了什么?除了最后一种方法,还有更好的方法吗


谢谢。

你的可观测目标应该发射阵列本身,而不是阵列的元素。因此,您不会得到最后一项,而是得到整个数组本身

按如下方式修改代码以获取数组中的最后一项:

this.tutorials$
  .pipe(
   map( data => data.map(item => item.id)), // emit array
   concatMap(array=>from(array)), // emit array elements
   last() // get the last element
  )
  .subscribe( console.log ); 
最后一个操作符仅在可观察对象完成时发出一个项。我不知道你的教程$observable做了什么,但我猜这就是为什么没有返回任何内容的原因

此外,rxjs操作符对发出的项的序列进行操作,而不是对发出的项本身进行操作。如果您只想提取该数组的最后一个值,请在map()操作符中执行

this.tutorials$
  .pipe(
    // will error on empty array, be more defensive here
    map( data => data[data.length-1].id)
    )
  .subscribe( console.log ); // return 40, every time the tutorials$ emits

但我理解你的困惑,我在开始使用rxjs时犯了完全相同的错误…

有两件事你需要注意:

  • 这个.tutorials$是什么?它完成了吗?如果它只是一个Ajax请求,那么您就可以了,因为它会立即完成,但如果它是一个主题,而您从不调用
    this.tutorials$.complete()
    ,那么这个链将永远不会完成,因此
    last()
    不会发出任何消息,因为它不知道最后一个值何时出现

  • 正如您所提到的
    map(…)
    返回一个数组
    [10,20,30,40]
    ,但
    last()
    从其可观察的源发射最后一次发射。不是数组中的最后一项。所以实际上您可能只想使用
    map(ids=>ids[ids.length-1])


  • 请注意,当
    tutorials$
    完成时,这只会发出最后一个数组的last()值。是的,根据文章,源代码只发出一个数组。