javascript - 在非独立组件中使用 Pipe
我有一个没有独立组件的 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'.
仓库链接: https://github.com/giolongo/gle-angular-lib/tree/master/projects/hello-world-with-ngrx/src/lib
我该如何解决这个问题?
答案#1
外观是一个服务,不应出现在模块的 exports 中。如果您想导入它,可以在应用程序中使用此库时使用 importProvidersFrom(HelloWorldWithNgrxModule)。
...
providers: [HelloWorldFacade],
declarations: [HelloWorldWithNgrxComponent],
exports: [HelloWorldWithNgrxComponent, CommonModule]
})
export class HelloWorldWithNgrxModule { }
请确保将所有文件都添加到 public-api.ts 的导出中,只有这样构建才会工作。
你之所以收到那个错误,可能是因为你导入了组件,但没有导入使用该组件的模块。
export * from './lib/+state/hello-world.action';
export * from './lib/+state/hello-world.effects';
export * from './lib/+state/hello-world.facade';
export * from './lib/+state/hello-world.reducer';
export * from './lib/+state/hello-world.selector';
export * from './lib/hello-world-with-ngrx.component';
export * from './lib/hello-world-with-ngrx.service';
export * from './lib/hello-world-with-ngrx.module';
