假设我有这个组件:
@Component({
selector: 'pizza-dialog',
template: `
<h1 md-dialog-title>Would you like to order pizza?</h1>
<md-dialog-actions>
<button (click)="dialogRef.close('yes')">Yes</button>
<button md-dialog-close>No</button>
</md-dialog-actions>
`
})
export class PizzaDialog {
constructor(public dialogRef: MdDialogRef<PizzaDialog>) { }
}
我已将MdDialog导入我的app模块:
@NgModule({
imports: [
BrowserModule,
MaterialModule.forRoot(),
MdDialogModule.forRoot(),
],
...
})
为什么我会收到此错误?
没有MdDialogRef的提供者!
答案 0 :(得分:24)
您可能尝试在如下模板中使用对话框组件:
<pizza-dialog ...></pizza-dialog>
从模板中删除它并使用MdDialog.open()打开对话框,如下所示:
@Component({
selector: 'pizza-component',
template: `
<button type="button" (click)="openDialog()">Open dialog</button>
`
})
export class PizzaComponent {
dialogRef: MdDialogRef<PizzaDialog>;
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
答案 1 :(得分:9)
您不得更改您的实施。 您可以为MdDialogRef提供模拟。 在下面的示例中,我使用 MdDialogRefMock 类伪造了MdDialogRef,并将其注册在提供程序部分中:
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<MessageBoxYesNoComponent>;
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,你也可以创建一个间谍而不是创建假类:
let mdDialogSpy = jasmine.createSpy('MdDialogRef');
答案 2 :(得分:0)
从模板中删除@Column
,它只需要打开Dialong的按钮,因为在代码中你设置了与对话框的关系。
答案 3 :(得分:0)
将MdDialogRef
添加到模块的提供者