如何在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
我用过:
defaultLang: (new LanguageService).getDefaultLanguage(),
defaultLang: inject(LanguageService).getDefaultLanguage(),
所有这些都显示注入上下文错误 那么,是否可以在ApplicationConfig中使用Service呢?
据我所知,在从
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,
}),
],
});
});