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

Angular注册用户添加至Firestore遇NG0203错误求助

解决Angular注册时NG0203: inject()必须在注入上下文中调用的问题

常见错误原因及修复步骤

1. 服务中错误地在方法回调内使用inject()

如果你的AuthService里存在类似下面的写法(在Promise回调中直接调用inject()):

@Injectable({ providedIn: 'root' })
export class AuthService {
  signup(email: string, password: string, userData: any) {
    return this.auth.createUserWithEmailAndPassword(email, password)
      .then((userCredential) => {
        // 错误:在回调函数内使用inject(),不在注入上下文
        const firestore = inject(Firestore);
        return collection(firestore, 'users').doc(userCredential.user?.uid).set(userData);
      });
  }
}

修复方法:将Firestore依赖移到服务的构造函数或类顶部注入:

@Injectable({ providedIn: 'root' })
export class AuthService {
  // 方式1:Angular 14+支持的类顶部注入
  private firestore = inject(Firestore);
  private auth = inject(Auth);

  // 方式2:传统构造函数注入(新手更易理解)
  // constructor(private firestore: Firestore, private auth: Auth) {}

  signup(email: string, password: string, userData: any) {
    return this.auth.createUserWithEmailAndPassword(email, password)
      .then((userCredential) => {
        if (!userCredential.user) throw new Error('用户创建失败');
        return collection(this.firestore, 'users').doc(userCredential.user.uid).set(userData);
      });
  }
}

2. 组件中错误地在普通方法内使用inject()

如果你的signup.component.ts第28行是在表单提交等方法内直接调用inject(),比如:

export class SignupComponent {
  onSubmit(form: NgForm) {
    // 错误:在组件方法内使用inject(),不在注入上下文
    const authService = inject(AuthService);
    authService.signup(form.value.email, form.value.password, form.value)
      .catch(err => console.error(err));
  }
}

修复方法:组件必须通过构造函数注入服务:

export class SignupComponent {
  // 构造函数注入AuthService
  constructor(private authService: AuthService) {}

  onSubmit(form: NgForm) {
    this.authService.signup(form.value.email, form.value.password, form.value)
      .catch(err => console.error(err));
  }
}

3. 确认服务的装饰器配置正确

检查AuthService是否添加了@Injectable()装饰器,并且providedIn配置为'root'或指定模块,确保Angular能识别它是可注入的服务:

// 正确的服务装饰器配置
@Injectable({ providedIn: 'root' })
export class AuthService {
  // ...
}

新手必知规则

Angular的inject()函数只能在注入上下文中调用:

  • 类的构造函数内部
  • @Injectable()装饰的服务类顶部(Angular 14+)
  • 依赖注入的工厂函数内
    绝对不能在普通方法、Promise回调、RxJS订阅回调等场景直接调用inject()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 06:16:01