如何在ApplicationConfig中注入Service?

问题描述 投票:0回答:1

如何在ApplicationConfig中注入Service?

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(appRoutes),
    provideTransloco({
      config: {
        availableLangs: ['en', 'ru', 'kk'],
        defaultLang: LanguageService.getDefaultLanguage(),
        reRenderOnLangChange: true,
        prodMode: !isDevMode(),
      },
      loader: TranslocoHttpLoader,
    }),
  ],
};

这里,我想使用LanguageService

我用过:

  1. defaultLang: (new LanguageService).getDefaultLanguage(),
  2. defaultLang: inject(LanguageService).getDefaultLanguage(),

所有这些都显示注入上下文错误 那么,是否可以在ApplicationConfig中使用Service呢?

angular dependency-injection translation angular-dependency-injection transloco
1个回答
0
投票

据我所知,在从

app_initializer
获取 API 之前不可能推迟环境提供程序,因此我获取 API 并获取默认语言,然后在收到响应后引导应用程序。

export function initializeApp(): Promise<any> {
  // fetch("https://someUrl.com/api/user") // <- place your API here!
  return firstValueFrom(
    of({ defaultLang: 'en' }) // simulate api call
  );
}

initializeApp().then((data: any) => {
  bootstrapApplication(App, {
    providers: [
      provideHttpClient(),
      provideTransloco({
        config: {
          availableLangs: ['en', 'es'],
          defaultLang: data.defaultLang,
          // Remove this option if your application doesn't support changing language in runtime.
          reRenderOnLangChange: true,
          prodMode: false,
        },
        loader: TranslocoHttpLoader,
      }),
    ],
  });
});

完整代码:

import {
  Component,
  APP_INITIALIZER,
  makeEnvironmentProviders,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { HttpClient, provideHttpClient } from '@angular/common/http';
import { provideTransloco, TranslocoModule } from '@jsverse/transloco';
import { firstValueFrom, tap, of } from 'rxjs';
import { TranslocoHttpLoader, LanguageService } from './transloco-loader';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [TranslocoModule],
  template: `
  asdf
  <ng-container *transloco="let t">
      <p>{{ t('home') }}</p>
  </ng-container> 
  `,
})
export class App {
  name = 'Angular';
}

export function initializeApp(): Promise<any> {
  // fetch("https://someUrl.com/api/user") // <- place your API here!
  return firstValueFrom(
    of({ defaultLang: 'en' }) // simulate api call
  );
}

initializeApp().then((data: any) => {
  bootstrapApplication(App, {
    providers: [
      provideHttpClient(),
      provideTransloco({
        config: {
          availableLangs: ['en', 'es'],
          defaultLang: data.defaultLang,
          // Remove this option if your application doesn't support changing language in runtime.
          reRenderOnLangChange: true,
          prodMode: false,
        },
        loader: TranslocoHttpLoader,
      }),
    ],
  });
});

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.