Angular 19非独立组件使用AsyncPipe编译报错的解决咨询
Angular 19非独立组件使用AsyncPipe编译报错的解决咨询
问题描述
我在Angular 19中创建了一个非独立组件,组件代码如下:
import { Component, inject, OnInit } from '@angular/core'; import { HelloWorldFacade } from './+state/hello-world.facade'; import { Observable } from 'rxjs'; import { CommonModule, DatePipe } from '@angular/common'; @Component({ selector: 'lib-hello-world-with-ngrx', standalone: false, template: ` {{message$ | async}} `, styles: `` }) export class HelloWorldWithNgrxComponent implements OnInit{ public message$?: Observable<string>; private hwFacade = inject(HelloWorldFacade); ngOnInit(): void { this.message$ = this.hwFacade.message$ setInterval(() => { this.hwFacade.appendMessage('a'); }, 10000); } }
对应的模块代码:
import { CommonModule, AsyncPipe } from '@angular/common'; import { NgModule } from '@angular/core'; import { EffectsModule } from '@ngrx/effects'; import { StoreModule } from '@ngrx/store'; import { HelloWorldEffects } from './+state/hello-world.effects'; import { HelloWorldFacade } from './+state/hello-world.facade'; import * as fromHW from './+state/hello-world.reducer'; import { HelloWorldWithNgrxComponent } from './hello-world-with-ngrx.component'; @NgModule({ imports: [ CommonModule, AsyncPipe, StoreModule.forFeature( fromHW.HW_FEATURE_KEY, fromHW.hwReducer ), EffectsModule.forFeature([HelloWorldEffects]) ], providers: [HelloWorldFacade], declarations: [HelloWorldWithNgrxComponent], exports: [HelloWorldFacade, HelloWorldWithNgrxComponent, CommonModule] }) export class HelloWorldWithNgrxModule { }
我创建了一个无应用的工作区,专门用来生成个人库,但是执行ng build hello-world-with-ngrx命令时,收到如下编译错误:
✖ Compiling with Angular sources in Ivy partial compilation mode. projects/hello-world-with-ngrx/src/lib/hello-world-with-ngrx.component.ts:10:20 - error NG8004: No pipe found with name 'async'.
解决方案
这个报错的核心原因是你在NgModule的imports数组中错误地直接导入了AsyncPipe——Angular的NgModule规则里,imports只能引入其他NgModule,不能单独导入管道、组件或指令。而AsyncPipe其实是CommonModule的一部分,只要模块正确导入CommonModule,组件模板就能正常使用这个管道。
具体修复步骤如下:
- 打开你的
HelloWorldWithNgrxModule,移除imports数组中的AsyncPipe:
@NgModule({ imports: [ CommonModule, // 删除这一行:AsyncPipe, StoreModule.forFeature( fromHW.HW_FEATURE_KEY, fromHW.hwReducer ), EffectsModule.forFeature([HelloWorldEffects]) ], providers: [HelloWorldFacade], declarations: [HelloWorldWithNgrxComponent], exports: [HelloWorldFacade, HelloWorldWithNgrxComponent, CommonModule] }) export class HelloWorldWithNgrxModule { }
- 确认
CommonModule已经保留在imports数组中(你当前代码已经添加了,这一步无需额外操作),它会自动提供AsyncPipe供组件模板使用。
完成修改后,重新执行ng build hello-world-with-ngrx,编译错误应该就能解决了。
备注:内容来源于stack exchange,提问作者giolongo
相关产品推荐
相关产品推荐

