[英]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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.