【问题标题】:How to get last emitted value of on Observable in the subscription when next is called after the subscription?订阅后调用 next 时,如何获取订阅中 Observable 的最后发出值?
【发布时间】:2021-07-30 08:32:03
【问题描述】:

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

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

    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();
  }
}

【问题讨论】:

  • 您的示例已经记录了123,不清楚您要在这里实现什么。
  • 抱歉编辑我的问题,我只想打印123 订阅最后一个发出的值,这就是为什么我尝试使用last()
  • 如果我理解正确,take(1) 应该这样做
  • @MrkSef no take(1) 只记录初始值stackblitz.com/edit/…

标签: angular rxjs


【解决方案1】:

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

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

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

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

您的StackBlitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多