[英]How to get last emitted value of on Observable in the subscription when next is called after the subscription?
How can I subscribe and log the last value when next is called after subscription?订阅后调用 next 时,如何订阅并记录最后一个值?
Here is the working demo stackblitz , how or is it possible to get value only the last value ie 123
that is emitted after the subscription inside the subscribe method or any other alternative?这是工作演示 stackblitz ,如何或有可能仅获取最后一个值,即123
在 subscribe 方法或任何其他替代方法中订阅后发出的值? I used last()
but it doesn't logs any value at all.我使用了last()
但它根本不记录任何值。 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();
}
}
You cannot use last()
as the subject does not currently complete.您不能使用last()
,因为主题当前未完成。 You need to call complete()
on the subject to be able to use it:您需要在主题上调用complete()
才能使用它:
ngOnInit() {
this.subject.next(456);
this.getData()
.pipe(last())
.subscribe(console.log);
this.subject.next(123);
this.subject.complete();
}
Your StackBlitz你的StackBlitz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.