简体   繁体   English

如何为 MatDialog 提供服务

[英]How to provide service to MatDialog

I am creating component for matDialog.我正在为 matDialog 创建组件。

this.matDialog.open(SegmentDialogComponent, { data: segment }})
  .afterClosed()
  .pipe(
    take(1),
    filter((i: any) => i)
  ).subscribe((i: CLASS) => this.update.emit(i) );

How I can provide service (that would implement ITableSegmentService interface) that SegmentDialogComponent can use我如何提供 SegmentDialogComponent 可以使用的服务(将实现 ITableSegmentService 接口)

export interface ITableSegmentService {
 addSegment<T>(body: T): Observable<T>;
 removeSegment(id: string): Observable<void>
}

. .

@Component({
  selector: 'segment-dialog',
  templateUrl: './segment-dialog.component.html',
  styleUrls: ['./segment-dialog.component.scss']
})

export class SegmentDialogComponent {

 constructor(@Inject(MAT_DIALOG_DATA) public tableSegment: TableSegment) { }

}

You can create the service (not an interface) and add it to the respective providers module.您可以创建服务(不是接口)并将其添加到相应的提供程序模块中。 (ex: app.module.ts) Then you just need to declare it on the constructor, like: (例如:app.module.ts)然后你只需要在构造函数中声明它,比如:

constructor(
  @Inject(MAT_DIALOG_DATA) public tableSegment: TableSegment,
  private tableSegmentService: TableSegmentService 
) { }

If you want to have more than one TableSegmentService type you need to use the @Inject to specify the service you want to inject.如果你想拥有多个 TableSegmentService 类型,你需要使用 @Inject 来指定你想要注入的服务。

I solved it like this:我是这样解决的:

Here for matDialogRef I provide service to that component that matDialog is using对于 matDialogRef,我为 matDialog 正在使用的组件提供服务

  openEditDialog(): void {
    let instance = this.matDialog.open(SegmentDialogComponent);

    instance.componentInstance.service = this.dynamicService (type is 
 TableSegmentService);
}

Later in that Dialog component I can use service methods and provide it with data --- Mat Dialog Class ----稍后在 Dialog 组件中,我可以使用服务方法并为其提供数据 --- Mat Dialog Class ----

export class SegmentDialogComponent {
  service!: ITableSegmentService;
formData: any;
  addSegment() {
this.service.addSegment(this.formData)
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM