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

Angular中如何向普通类注入服务?遇NG0203等问题求助

Angular普通类注入服务的问题解决

问题原因分析

  1. NG0203错误:inject()函数仅能在Angular的注入上下文(如@Injectable/@Component类的构造函数、DI工厂函数等)中调用。手动new ModelStructure()时,构造函数不在该上下文内,因此触发此错误。
  2. 注入令牌错误:添加@Injectable装饰器后,Angular DI会尝试解析构造函数的所有参数,但type和form_id是普通数值类型,不属于Angular可识别的注入令牌(如服务类、InjectionToken),因此报错。

解决方案

方案一:手动传入依赖(最直接)

修改构造函数,将DataService作为参数传入,调用时从注入上下文(如组件、其他服务)中获取该服务并传递:

import { DataService } from './your-data-service-path';

export class ModelStructure {
    constructor(
        private type: number,
        private form_id?: number,
        private dataService: DataService
    ) {}

    // 示例:使用dataService
    fetchData() {
        return this.dataService.getData();
    }
}

// 调用示例(组件中)
import { Component } from '@angular/core';

@Component({/* ... */})
export class YourComponent {
    constructor(private dataService: DataService) {}

    createModel() {
        const model = new ModelStructure(1, 2, this.dataService);
        model.fetchData();
    }
}

方案二:通过Injector获取服务

如果不想让调用方直接传递DataService,可以让ModelStructure接收Injector参数,再通过Injector获取服务:

import { Injector } from '@angular/core';
import { DataService } from './your-data-service-path';

export class ModelStructure {
    private dataService: DataService;

    constructor(
        private type: number,
        private form_id?: number,
        injector: Injector
    ) {
        this.dataService = injector.get(DataService);
    }
}

// 调用示例(组件中)
import { Component, Injector } from '@angular/core';

@Component({/* ... */})
export class YourComponent {
    constructor(private injector: Injector) {}

    createModel() {
        const model = new ModelStructure(1, 2, this.injector);
    }
}

方案三:使用静态工厂函数(适配DI场景)

如果需要同时支持手动创建和DI创建,可以写一个静态工厂函数,在函数内利用inject()获取服务:

import { inject } from '@angular/core';
import { DataService } from './your-data-service-path';

export class ModelStructure {
    constructor(
        private type: number,
        private form_id?: number,
        private dataService: DataService
    ) {}

    // 静态工厂方法,在注入上下文内调用
    static create(type: number, form_id?: number) {
        return new ModelStructure(type, form_id, inject(DataService));
    }
}

// 调用示例(组件或服务中)
const model = ModelStructure.create(1, 2);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 08:36:59