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

Angular 19中inject()需从注入上下文调用错误排查求助

Angular 19登录组件NullInjectorError问题的调试与排查

我刚学习Angular,若有明显疏漏还请见谅。我在主页面中使用了一个简单的登录组件,只要把这个组件从app.component.html中移除,程序就能正常运行,所以确定问题出在该组件上。我完全按照文档要求在构造函数中使用了inject,也尝试过在声明中直接初始化,但都出现了NullInjectorError错误。当前使用的是Angular 19.x版本。

相关代码

login.component.html

@if (isLoggedIn) {
  <div>{{ loginName }}</div>
}
@else {
  <div (click)="signInWithGoogle()">Log In</div>
}

login.component.ts

import { Component, inject, ProviderToken } from '@angular/core';
import { AuthGoogleService } from '../services/auth-google.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrl: './login.component.css',
  standalone: true,
  providers: [AuthGoogleService],
})
export class LoginComponent {
  private authService: AuthGoogleService;
  isLoggedIn: boolean = false;
  loginName: string = '';

  signInWithGoogle() {
    this.authService.login();
  }

  constructor() {
    this.authService = inject(AuthGoogleService);
    this.isLoggedIn = false;
  }
}

AuthGoogleService类代码

import { Injectable, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
import { AuthConfig, OAuthService } from 'angular-oauth2-oidc';
import { authConfig } from './auth.config';

@Injectable({
  providedIn: 'root',
})

export class AuthGoogleService {
  private oAuthService = inject(OAuthService);
  private router = inject(Router);
  profile = signal<any>(null);

  constructor() {
    this.initConfiguration();
  }

  initConfiguration() {
    this.oAuthService.configure(authConfig);
    this.oAuthService.setupAutomaticSilentRefresh();
    this.oAuthService.loadDiscoveryDocumentAndTryLogin().then(() => {
      if (this.oAuthService.hasValidIdToken()) {
        this.profile.set(this.oAuthService.getIdentityClaims());
      }
    });
  }

  login() {
    this.oAuthService.initImplicitFlow();
  }

  logout() {
    this.oAuthService.revokeTokenAndLogout();
    this.oAuthService.logOut();
    this.profile.set(null);
  }

  getProfile() {
    return this.profile();
  }
}

调试方法与检查项

  • 移除重复的服务注册:AuthGoogleService已经通过@Injectable({providedIn: 'root'})注册为根级别服务,但你又在LoginComponent的providers数组中再次声明。这会导致组件创建一个独立的服务实例,而该实例依赖的OAuthService未在组件层级注册。直接删除LoginComponent元数据里的providers: [AuthGoogleService]即可。
  • 验证OAuthService的注册:angular-oauth2-oidc的OAuthService需要正确注册。如果是独立组件架构,要确保在组件的imports数组中添加OAuthModule.forRoot(),或者在根配置中完成注册。
  • 用Angular DevTools检查注入器:安装Angular DevTools扩展,打开组件树找到LoginComponent,查看其注入器中的服务实例,确认AuthGoogleService和OAuthService是否存在。
  • 简化注入逻辑:把组件中authService的声明改为直接注入,去掉构造函数里的赋值:
    private authService = inject(AuthGoogleService);
    
    这样更符合Angular 19的注入规范,也能避免构造函数中的潜在问题。
  • 查看完整错误栈:打开浏览器控制台,复制完整的NullInjectorError信息,错误会明确指出哪个服务找不到提供者(格式通常是NullInjectorError: No provider for XXX),根据这个信息直接定位缺失的依赖。
  • 检查auth.config.ts的有效性:确认auth.config.ts文件存在,且authConfig已正确导出,配置内容没有语法错误。如果这个文件有问题,会导致AuthGoogleService初始化失败,间接引发注入错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:20:02