You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 18中APP_INITIALIZER无法注入依赖问题求助

Angular 18独立组件项目APP_INITIALIZER依赖注入失效问题

项目代码

main.ts

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

appConfig.ts

import {
  APP_INITIALIZER,
  ApplicationConfig,
  provideZoneChangeDetection,
} from '@angular/core';
import { provideRouter, Router } from '@angular/router';

import { routes } from './app.routes';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideToastr } from 'ngx-toastr';
import { onAppStart } from './app.initialiser';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideAnimations(), // required animations providers
    provideToastr(), // Toastr providers
    {
      provide: APP_INITIALIZER,
      useValue: onAppStart,
      multi: true,
      deps: [Router],
    },
  ],
};

app.initialiser.ts

import { Router } from '@angular/router';

export function onAppStart(router: Router): Promise<any> {
  return new Promise((resolve, reject) => {
    console.log(router);
    resolve(true);
  });
}

问题描述

运行应用时,app.initialiser.ts中的router参数为undefined,配置的deps依赖完全未生效,请问问题出在哪里?


问题原因与修复方案

核心错误

配置APP_INITIALIZER时使用了useValue,但useValue不会触发Angular的依赖注入机制——它只会直接传入你指定的函数,不会自动注入deps里声明的依赖。

修复步骤

将useValue替换为useFactory,Angular才会识别deps数组并完成依赖注入:

修改appConfig.ts中的APP_INITIALIZER配置项:

{
  provide: APP_INITIALIZER,
  useFactory: onAppStart, // 替换useValue为useFactory
  multi: true,
  deps: [Router],
},

原理说明

  • useValue:适用于提供静态值(常量、已实例化对象或无需依赖注入的函数),Angular不会对其做依赖注入处理。
  • useFactory:适用于需要依赖注入的工厂函数,Angular会根据deps数组自动注入所需服务实例,再调用该函数。

修改后重启应用,router参数就能正常获取到Router实例了。

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 09:56:02