Observable的最后发出值

Observable的最后发出值

本文介绍了订阅后调用next时如何获取订阅中on Observable的最后发出值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何订阅并记录订阅后调用 next 时的最后一个值?

How can I subscribe and log the last value when next is called after subscription ?

这是工作演示 stackblitz,如何或是否有可能仅获取在订阅方法或任何其他替代方法中订阅后发出的最后一个值,即123?我使用了 last() 但它根本不记录任何值.我希望订阅只运行一次并使用最后一个值

Here is the working demo stackblitz, how or is it possible to get value only the last value i.e.123 that is emitted after the subscription inside the subscribe method or any other alternative ? I used last() but it doesn't logs any value at all. I want the subscription to run only once and use the last value

    import { Component, Input, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { last } from 'rxjs/operators';

@Component({
  selector: 'hello',
  template: `
    <h1>Hello {{ name }}!</h1>
  `
})
export class HelloComponent implements OnInit {
  @Input() name: string;
  subject = new BehaviorSubject<any>({});

  ngOnInit() {
    this.subject.next(456);

    this.getData()
      // .pipe(last())
      .subscribe(console.log);

      // this next is being done in another component after subscription so putting it here to mimic the behavior
     this.subject.next(123);

  }

  getData(): Observable<any> {
    return this.subject.asObservable();
  }
}

推荐答案

您不能使用 last() 因为该主题当前未完成.您需要在主题上调用 complete() 才能使用它:

You cannot use last() as the subject does not currently complete. You need to call complete() on the subject to be able to use it:

ngOnInit() {
  this.subject.next(456);

  this.getData()
    .pipe(last())
    .subscribe(console.log);

  this.subject.next(123);
  this.subject.complete();
}

您的 StackBlitz

Your StackBlitz

这篇关于订阅后调用next时如何获取订阅中on Observable的最后发出值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!