网站搜索

typescript - Angular Material Snackbar 的 StaticInjectorError


我想将 Material Snackbar 作为服务添加到我的应用中。

所以,在我的 notification.service.ts 中,我添加了:

import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class NotificationService {

  snackbar_notification: Subject<string> = new Subject();
  constructor() {}
  setSnackbarNotification(message: string) {
    this.snackbar_notification.next(message);
  }
}

在我的 app.component.ts 中:

export class AppComponent implements OnInit {

  constructor(
    private notificationService: NotificationService,
    public snackBar: MatSnackBar
  ) {

    this.notificationService.snackbar_notification.subscribe(message => {
      this.snackBar.open(message);
    });

  }
}

我从一个组件中触发 snackbar,如下所示:

this.notificationService.setSnackbarNotification('this is a notification');

在我对上述三个文件做了上述更改之前,代码运行得很好。

现在,它在执行过程中给我报错:

Error: StaticInjectorError(Xs)[e -> e]: 
  StaticInjectorError(Platform: core)[e -> e]: 
    NullInjectorError: No provider for e!

我该如何解决这个问题?

答案#1

导入模块:

import {MatSnackBarModule} from '@angular/material/snack-bar'; 

并将其添加到你的模块中:

@NgModule({
    imports: [
        MatSnackBarModule,
    ],
    providers: [

    ],
})

确保你正在添加到通知和你在其中使用的组件的父模块中。