首页 > 解决方案 > 在启动时调用 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();
      }
    });
  }
}

标签: angularsubscriptioninitializer

解决方案


推荐阅读