簡體   English   中英

環境來自后端時的服務工作者注冊

[英]Service worker registration when environment comes from the backend

Angular v14。 我正在使用https://timdeschryver.dev/blog/angular-build-once-deploy-to-multiple-environments#platformbrowserdynamic實現從 main.ts 中的后端獲取環境並將其添加到提供程序中。

要訪問我使用的服務中的環境(this._config.environment.isProduction):

export class AppInitService {
  constructor(
    @Inject(APP_CONFIG) private _config: IAppConfig,
  ) {}
}

但是通過這個實現,我不知道如何根據 app.module.ts 中的環境啟用/禁用服務工作者。

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ServiceWorkerModule.register('ngsw-worker.js', {
       enabled: true, // should use from providers environment variable
      registrationStrategy: 'registerImmediately',
    })  ]})
export class AppModule {}

由於它是模塊,我找不到如何注入和訪問我的 _config.environment.isProduction boolean。

我嘗試從 app.module.ts 中刪除服務人員並在 main.ts 中注冊服務人員

    platformBrowserDynamic(providers)
      .bootstrapModule(AppModule)
      .then(() => {
          // isProduction is boolean from API response
        if ('serviceWorker' in navigator && isProduction) {
          navigator.serviceWorker.register('ngsw-worker.js');
        }
      })
      .catch((err) => console.log(err));

但是依賴服務工作者的服務(例如用於處理更新的 SwUpdate)在瀏覽器中給出錯誤

NullInjectorError: R3InjectorError(AppModule)[UpdateService -> SwUpdate -> SwUpdate -> SwUpdate]: NullInjectorError: 沒有 SwUpdate 的提供者!

更新.service.ts

@Injectable({
  providedIn: 'root',
})
export class UpdateService {
  constructor(private swUpdate: SwUpdate) {
    if (swUpdate.isEnabled) {
      swUpdate.versionUpdates.subscribe((event) => {
        switch (event.type) {
          case 'VERSION_READY':
            swUpdate.activateUpdate().then(() => {
              document.location.reload();
            });
            break;
        }
      });
    }
  }
}

我在 App.component.ts 構造函數中注冊它

export class AppComponent implements OnInit {
  constructor(
    private updateService: UpdateService,
  ) {
  }

所以我的問題是我該怎么做:

  1. 將來自提供者的變量注入 app.module.ts 以在啟用時使用:my_injected_isProduction_boolean 繼續手動注冊
  2. main.ts 但在我的服務中有 SwUpdate 工作

如果我在 main.ts 和 app.modules 中保留我的注冊,我會禁用注冊

ServiceWorkerModule.register('ngsw-worker.js', {
  enabled: false,
}),

它確實根據 main.ts 注冊服務工作者並且加載正常,但它似乎令人困惑,並且不確定它是否會在此過程中剎車。 想要一些清晰的東西在一個地方。

顯然它就像使用https://angular.io/api/service-worker/SwRegistrationOptions一樣簡單

  imports: [
    ServiceWorkerModule.register('ngsw-worker.js'),
  ],
  providers: [
    {
      provide: SwRegistrationOptions,
      useFactory: (config: ConfigService) => ({enabled: this.config.isEnabled}),
      deps: [ConfigService]
    },
  ],

在 APP_INITIALIZER 中執行的后端響應必須使用 await 設置,以便在引導完成和讀取 yourConfigService 值時具有值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM