angular - 在启动时调用 PWA 服务,该服务返回对可观察对象的订阅
问题描述
我正在尝试PWAService
在应用程序启动时调用。此服务返回订阅:
@Injectable({
providedIn: 'root'
})
export class PwaService {
constructor(
private swUpdate: SwUpdate,
private translateService: TranslateService
) { }
public checkForAppUpdate(): Subscription | undefined {
if (this.swUpdate.isEnabled) {
return this.swUpdate.available.subscribe(() => {
const appNewVersion = this.translateService.instant('app.new_version_available');
if (confirm(appNewVersion)) {
window.location.reload();
}
});
}
}
}
当它返回一个订阅时,我倾向于保留订阅引用,以便以后不再需要服务时取消订阅,即应用程序停止时。即使这种停止可能永远不会真正发生,我仍然在考虑启用退订。
this.swUpdateSubscription = this.pwaService.checkForAppUpdate();
if (this.swUpdateSubscription != null) {
this.swUpdateSubscription.unsubscribe();
}
使用一些回调会很方便ngOnInit()
,ngOnDestroy()
但我没有任何要渲染的标记,所以没有模板。因此,我认为我不能使用组件或指令。
我知道我可以通过以下方式调用我的服务PWAModule
:
const pwaFactory = (pwaService: PwaService) => () => pwaService.checkForAppUpdate();
@NgModule({
imports: [
ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: pwaFactory,
deps: [ PwaService ],
multi: true
}
]
})
export class PwaModule { }
但是上面的调用pwaService.checkForAppUpdate()
并没有保存对返回订阅的引用。
如果需要,如何保存此订阅参考以便以后取消订阅?
另外,我不需要在应用程序启动时间之前调用此服务,它可以在启动后调用。我希望这项服务不会阻塞也不会延迟应用程序启动。
我知道我的设计和我看待问题的方式可能不正确。
更新:我可以解决这个问题并将订阅保存在服务中。事实上,该服务可以有一个ngOnDestroy()
方法,我可以在其中执行取消订阅:
private pwaCheckForUpdateSubscription?: Subscription;
ngOnDestroy() {
if (this.pwaCheckForUpdateSubscription != null) {
this.pwaCheckForUpdateSubscription.unsubscribe();
}
}
public checkForAppUpdate(): void {
if (this.swUpdate.isEnabled) {
this.pwaCheckForUpdateSubscription = this.swUpdate.available.subscribe(() => {
const appNewVersion = this.translateService.instant('app.new_version_available');
if (confirm(appNewVersion)) {
this.uiService.reloadPage();
}
});
}
}
解决方案
推荐阅读
- ios - Ionic v1 src=unsafe 对于所有最新的 Cordova-ios@5.1.1 图像
- c# - 在 Powershell 中从非常大的 XML 文件中删除节点
- javascript - request.pipe() 和大文件的节点问题,错误:无法创建长度超过 0x1fffffe8 个字符的字符串
- python - bulk_update 能否更新某些记录失败但整体成功?
- python - How to find common elements at the same indices in two lists
- sql - 如何计算插入表单的数据数量
- python - py2neo:为什么使用类属性?
- r - 有没有更好的方法来为 tibble 中的每个键(sym)添加一个新的值/字段,而不是使用 mutate 然后 pivot_longer?
- apache-spark - 从 HDFS 目录读取 csv 文件时无法修复 UnknownHostException
- javascript - 如何在再次调用 **SET-INTERVAL** 中的函数之前“等待”API 的响应