当前位置:  开发笔记 > 开发工具 > 正文

"没有MdDialogRef的提供者!"

如何解决《"没有MdDialogRef的提供者!"》经验,为你挑选了2个好方法。

假设我有这个组件:

@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



1> Alexander Ta..:

您可能试图在模板中使用对话框组件,如下所示:


从模板中删除它并使用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



2> 小智..:

您不得更改您的实施.您可以为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');

推荐阅读
落单鸟人
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有