首页 > 解决方案 > 如何在 Angular 9 中将对话框注入到服务中

问题描述

我想将 aMatDialog注入服务而不将其初始化到构造函数中。可能吗 ?如果是,我怎么能做到这一点?目标是将服务调用到一个类中,稍后我将不得不在该类中注入 MatDialog 和其他组件

这是我的实现

ClassBook {
  private bookService: BookService = new BookService(); // no parameters hence the empty constructor

  public createBook(book: Book){
     this.bookService.addBook(book);
  }
}

export class BookService{
    constructor() { }
    
    // if i just call this, the this.dialog.open will be undefined
    public dialog: MatDialog;

 
    public addBook(book){
      const dialogRef = this.dialog.open(BookDialog, {
          width: '500px',
          disableClose: true
          data: {
             book
          }
      });
   }
}

标签: dependency-injectionangular9

解决方案


我将在 AppModule 中使用静态注入器,然后在我需要的类中将其称为单例


推荐阅读