我有一个共享模块,其中包含通用组件,例如标头和通知组件。我还有另一个名为ProductModule的模块,该模块使用共享模块中的通知组件并调用在通知组件中定义的函数。
shared.module.ts
@NgModule({
declarations: [
HeaderComponent,
SideNavComponent,
SpinnerComponent,
ItemSummaryComponent,
UserRoleDirective,
EmptyResultComponent,
NotificationComponent
],
imports: [
CommonModule,
RouterModule,
MatProgressSpinnerModule,
MatIconModule
],
exports: [
HeaderComponent,
SideNavComponent,
SpinnerComponent,
ItemSummaryComponent,
EmptyResultComponent,
NotificationComponent
],
})
export class SharedModule {}
notification.component.ts
export class NotificationComponent {
openSnackBar(message: string, state: string, icon: string): void {
const config = new MatSnackBarConfig();
config.duration = 3000;
config.panelClass = ['nc-notification', state];
config.data = { message, icon };
this._snackBar.openFromComponent(NotificationComponent, config);
}
}
在我的延迟加载productModuel
中,我已按如下所示导入sharedModule
。
import { CommonCmpsModule } from '../common-cmps/common-cmps.module';
import { TaxConfigurationComponent } from './tax-configuration/tax-configuration.component';
@NgModule({
declarations: [
TaxConfigurationComponent
],
imports: [
SharedModule,
]
})
export class ProductModule { }
在我的TaxConfigurationComponent
中,我想使用通知组件并调用openSnackBar函数。
TaxConfiguration.component.ts
import { NotificationComponent } from 'src/app/common-cmps/notification/notification.component';
export class TaxConfigurationComponent {
constructor(
private notificationService: NotificationService
){}
onClickSave(): void {
this.notificationService.openSnackBar('An Error Occurred', 'nc-notification--error', 'close');
}
}
但是,我在浏览器控制台中遇到了错误。
错误错误:未捕获(已承诺):NullInjectorError:R3InjectorError(ProductManagementModule)[NotificationComponent-> NotificationComponent-> NotificationComponent-> NotificationComponent]: NullInjectorError:NotificationComponent没有提供者!
答案 0 :(得分:1)
构造函数用于注入服务而不是组件。
对于组件,您有两个选择。
如果使用选择器,则可以使用@ViewChild获取通知组件实例并调用该方法。
如果不使用选择器,则创建一个带有主题的服务,并从taxconfiguration组件中对该主题调用.next。在通知组件中订阅该主题,并在订阅中调用您的opensnackbar方法。
答案 1 :(得分:0)
请勿对组件使用构造函数注入。在税收配置组件中,您正在使用
constructor(
private notificationCmp: NotificationComponent
){}
请删除该内容。
然后注入MatSnackBar
服务,该服务由以下材料提供
import {MatSnackBar} from '@angular/material/snack-bar';
constructor(private _snackBar: MatSnackBar) {}
这并使用您的自定义组件,如下所示
this._snackBar.openFromComponent(NotificationComponent, {
duration: 1500,
});
除此之外,您需要在模型内部添加NotificationComponent作为输入组件
entryComponents: [NotificationComponent],
答案 2 :(得分:0)
问题可能是您正在导入 NotificationComponent ,但是在构造函数中您正在引用 NotificationService 并尝试调用在 NotificationComponent 中定义的函数吗?