簡體   English   中英

訂閱后調用 next 時,如何獲取訂閱中 Observable 的最后發出值?

[英]How to get last emitted value of on Observable in the subscription when next is called after the subscription?

訂閱后調用 next 時,如何訂閱並記錄最后一個值?

這是工作演示 stackblitz ,如何或有可能僅獲取最后一個值,即123在 subscribe 方法或任何其他替代方法中訂閱后發出的值? 我使用了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();
  }
}

您不能使用last() ,因為主題當前未完成。 您需要在主題上調用complete()才能使用它:

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

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

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

你的StackBlitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM