我正在尝试实现服务,无论应用程序是否与我的服务器建立连接,该服务都可观察到,因此当浏览器在线时,我们使用计时器ping服务器。这是代码:
@Html.DisplayFor(modelItem => item.StartDate.ToLongDateString())
public get $connected(): Observable<boolean> {
return this.hasInternetConnection
.asObservable()
.pipe(
distinctUntilChanged(),flatMap((connected: boolean) => {
if (!connected) {
return of(connected);
} else {
return timer(5000)
.pipe(
map(() => {
var success = Math.random() > 0.5;
console.log('PING: ' + success);
return success;
})
);
}
})
);
}
只是绑定到窗口hasInternetConnection
和online
事件的BehaviorSubject,计时器模拟对我的API服务器的ping。
问题是我的订阅offline
仅从可观察到的计时器中捕获第一个值,然后不起作用。在$connected
主题更改为hasInternetConnection
并返回到false
之后,我的订阅再次获得第一个值,然后什么都没有。这是我在控制台中看到的内容:
true
我该如何解决?谢谢!