假设我有这个组件:
@Component({ selector: 'pizza-dialog', template: `Would you like to order pizza?
` }) export class PizzaDialog { constructor(public dialogRef: MdDialogRef ) { } }
我已经将MdDialog导入了我的app模块:
@NgModule({ imports: [ BrowserModule, MaterialModule.forRoot(), MdDialogModule.forRoot(), ], ... })
为什么我会收到此错误?
没有MdDialogRef的提供商!
Alexander Ta.. 24
您可能试图在模板中使用对话框组件,如下所示:
从模板中删除它并使用MdDialog.open()打开对话框,如下所示:
@Component({ selector: 'pizza-component', template: ` ` }) export class PizzaComponent { dialogRef: MdDialogRef; constructor(public dialog: MdDialog) { } openDialog() { this.dialogRef = this.dialog.open(PizzaDialog, { disableClose: false }); this.dialogRef.afterClosed().subscribe(result => { console.log('result: ' + result); this.dialogRef = null; }); } }
此代码复制自:https: //github.com/angular/material2/blob/master/src/lib/dialog/README.md
您可能试图在模板中使用对话框组件,如下所示:
从模板中删除它并使用MdDialog.open()打开对话框,如下所示:
@Component({ selector: 'pizza-component', template: ` ` }) export class PizzaComponent { dialogRef: MdDialogRef; constructor(public dialog: MdDialog) { } openDialog() { this.dialogRef = this.dialog.open(PizzaDialog, { disableClose: false }); this.dialogRef.afterClosed().subscribe(result => { console.log('result: ' + result); this.dialogRef = null; }); } }
此代码复制自:https: //github.com/angular/material2/blob/master/src/lib/dialog/README.md
您不得更改您的实施.您可以为MdDialogRef提供模拟.在下面的示例中,我使用MdDialogRefMock类伪造了MdDialogRef,并在providers部分中注册它:
import { async, ComponentFixture, TestBed } from "@angular/core/testing"; import { CUSTOM_ELEMENTS_SCHEMA } from "@angular/core"; import { MessageBoxYesNoComponent } from "./message-box-yes-no.component"; import { MdDialogRef } from "@angular/material"; class MdDialogRefMock { } describe("MessageBoxYesNoComponent", () => { let component: MessageBoxYesNoComponent; let fixture: ComponentFixture; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ MessageBoxYesNoComponent ], schemas: [CUSTOM_ELEMENTS_SCHEMA], imports: [ ], providers: [ { provide: MdDialogRef, useClass: MdDialogRefMock } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MessageBoxYesNoComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it("should create", () => { expect(component).toBeTruthy(); }); });
如果您使用的是Jasmine,您还可以创建一个Spy而不是创建Fake-Class:
let mdDialogSpy = jasmine.createSpy('MdDialogRef');