【发布时间】: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/…