You need to enable JavaScript to run this app. Angular 11 出现Maximum call stack size exceeded报错该如何排查解决
优惠活动
大模型
产品
解决方案
定价
更多

Angular 11 出现Maximum call stack size exceeded报错该如何排查解决

问题原因

Error: Maximum call stack size exceeded报错由以下核心问题触发:

  • 错误注入非可注入类:UploadService构造函数中注入的User是auth.service中导出的用户数据模型(接口/普通实体类),并未添加@Injectable注解也没有在依赖注入列表中注册,Angular依赖注入器无法找到对应提供者,会触发无限递归的实例化重试,最终导致调用栈溢出。
  • 属性初始化时机错误:UploadService中直接在类属性声明阶段就取值this.user.uid,此时构造函数还未执行完成,就算注入逻辑正常也大概率会拿到未初始化的空值,引发后续逻辑异常。
解决方案

1. 修正UploadService依赖注入逻辑

删除对User模型的直接注入,改为注入NgAuthService动态获取当前登录用户ID,调整路径拼接逻辑到上传执行阶段:

import { Injectable } from '@angular/core';
import { AngularFireStorage } from '@angular/fire/storage';
import firebase from 'firebase/app';
import { NgAuthService } from '../auth/auth.service';

@Injectable({
  providedIn: 'root',
})
export class UploadService {
  constructor(
    private afStorage: AngularFireStorage, 
    private authService: NgAuthService
  ) { }

  file: File;
  url = '';

  // 按需获取当前登录用户ID
  private getCurrentUserId(): string {
    // 此处替换为你NgAuthService中实际获取当前登录用户的属性/方法名
    const currentUser = this.authService.currentUser;
    if (!currentUser?.uid) throw new Error('用户未登录,无法执行上传操作');
    return currentUser.uid;
  }

  async uploadFile(event) {
    this.file = event.target.files[0];
    if (this.file) {
      const basePath = `/uploads/images/${this.getCurrentUserId()}`;
      const filePath = `${basePath}/${this.file.name}`;
      const snap = await this.afStorage.upload(filePath, this.file);
      this.getUrl(snap);
    } else {
      alert('Please select an image'); 
    }
  }

  private async getUrl(snap: firebase.storage.UploadTaskSnapshot) {
    const url = await snap.ref.getDownloadURL();
    this.url = url;
    console.log(this.url);
  }
}

2. 可选优化:同步组件与服务的URL更新

user-profile.component.ts中直接赋值image = this.uploadService.url属于值类型拷贝,后续服务中url更新时组件属性不会同步变更,可改为getter实现动态取值:

import { Component, OnInit } from '@angular/core';
import { UploadService } from '../../storage/upload.service';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {
  constructor(private uploadService: UploadService) { }

  get image() {
    return this.uploadService.url;
  }

  ngOnInit(): void {
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 01:15:03