Angular 17类库中使用Font Awesome遇NG0203错误求助
解决Angular类库中使用Font Awesome图标时的NG0203错误
核心原因
这个错误是因为你在非注入上下文中调用了inject()函数,常见于类库组件里直接在组件方法、普通函数中使用Font Awesome的依赖注入API(比如FaIconLibrary),而非构造函数、工厂函数这类Angular允许的注入上下文。
正确使用方式
1. 构造函数中注入依赖
将Font Awesome的FaIconLibrary或其他需要的服务,直接在组件构造函数中注入,不要在组件其他方法里用inject()获取:
import { Component, OnInit } from '@angular/core'; import { FaIconLibrary } from '@fortawesome/angular-fontawesome'; import { faUser, faEdit } from '@fortawesome/free-solid-svg-icons'; @Component({ selector: 'lib-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { constructor(private library: FaIconLibrary) { // 在构造函数中添加需要的图标 library.addIcons(faUser, faEdit); } ngOnInit(): void { // 如需操作图标库,直接使用构造函数注入的library实例 } }
2. 避免静态方法/普通函数中调用inject()
如果类库中有工具函数或静态方法需要访问Font Awesome服务,绝对不能直接在里面调用inject(),可以通过两种方式处理:
- 将服务实例作为参数传递给函数
- 借助
Injector和runInInjectionContext包裹调用逻辑:
import { Injector, runInInjectionContext } from '@angular/core'; import { FaIconLibrary } from '@fortawesome/angular-fontawesome'; @Component({ selector: 'lib-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { constructor(private injector: Injector) {} someMethod() { runInInjectionContext(this.injector, () => { const library = inject(FaIconLibrary); // 在这里执行需要图标库的操作 }); } }
3. 类库模块的正确配置
在类库的NgModule中,确保导入Font Awesome模块,不要手动在providers中创建服务实例,交给Angular的DI系统处理:
import { NgModule } from '@angular/core'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { YourComponent } from './your-component.component'; @NgModule({ declarations: [YourComponent], imports: [FontAwesomeModule], exports: [YourComponent] }) export class YourLibraryModule { }
4. 字段注入的正确姿势
如果使用字段注入,仅在字段初始化时调用inject(),不要在后续代码中重复调用:
import { Component, inject } from '@angular/core'; import { FaIconLibrary } from '@fortawesome/angular-fontawesome'; @Component({ selector: 'lib-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { // 正确:仅在字段初始化时使用inject() private library = inject(FaIconLibrary); ngOnInit() { this.library.addIcons(...); } }
验证步骤
- 重新构建类库:
ng build your-library - 在测试项目中更新类库依赖,确保使用最新构建版本
- 运行测试项目,检查NG0203错误是否消失
内容的提问来源于stack exchange,提问作者Hartish Khoobarry
相关产品推荐
相关产品推荐

