[英]Trying to Subscribe to a method that returns an Observable in Angular
I have a method that returns an Observable:我有一个返回 Observable 的方法:
clockOut(): Observable<boolean> {
let isClockedOut = new Subject<boolean>();
isClockedOut.next(false);
// Some code to clock out and return x
if (x === true) {
isClockedOut.next(true);
}
return isClockedOut.asObservable();
}
And I'm calling/subscribing to the clockOut() method like so:我正在调用/订阅 clockOut() 方法,如下所示:
ngOnInit() {
this.clockOut().subscribe((didClockOut: boolean) => {
if (didClockOut === true) {
// Do stuff
}
});
}
The clockOut() method gets called, and the code inside clockOut() executes properly, but the code block after.subscribe is not being called.调用了clockOut() 方法,并且clockOut() 中的代码正确执行,但是没有调用after.subscribe 的代码块。 Almost like clockOut() isn't returning the Observable?
几乎就像clockOut() 没有返回Observable?
I'm new to Angular and I've not worked with Observables/Subjects much.我是 Angular 的新手,我对 Observables/Subjects 的使用并不多。 Any help is appreciated.
任何帮助表示赞赏。 Thanks!
谢谢!
The subject
does not return old events to new subscriptions, you are triggering, next before returning the observable, so those events are not subscribed yet. subject
不会将旧事件返回到新订阅,您正在触发 next 在返回可观察对象之前,因此这些事件尚未订阅。
also, you don't have any need for Subject
here since everything is synchronous.另外,这里不需要
Subject
,因为一切都是同步的。
if you want last event triggered you can use BehaviorSubject
instead of subject
如果你想触发最后一个事件,你可以使用
BehaviorSubject
而不是subject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.