coder925
coder925

Reputation: 432

How to share a scoped service with a component inside an MdDialog?

I have an app with an AppComponent parent, and a ProductComponent child. In the ProductComponent, I have provided a service because I want the service to be available only within the ProductComponent scope and below (for any future grandchild components). I do not want to provide the service globally at the root scope of NgModule.

@Component({
  selector: 'my-product',
  providers: [ MyService ],
  ...

My DialogComponent is dependent on the service. But when I open a dialog from ProductComponent...

export class ProductComponent {
  openDialog() {
    let dialogRef = this.dialog.open(DialogComponent);
  }  
}

...I get an exception: Error: No provider for MyService

How can I forward the provided service from ProductComponent to the DialogComponent?

Please see my minimal Plunker sample that shows the problem.

Upvotes: 2

Views: 359

Answers (2)

coder925
coder925

Reputation: 432

I managed to solve this issue after finding an identical issue described on GitHub.

You need to pass an MdDialogConfig to the dialog.open function setting viewContainerRef, like so:

openDialog() {
  let config = new MdDialogConfig();
  config.viewContainerRef = this.viewContainerRef;
  let dialogRef = this.dialog.open(DialogComponent, config);
}

Now the DialogComponent will get its dependent services injected from the parent ProductComponent. I have a new Plunker showing the solution.

Upvotes: 1

Aakash Thakur
Aakash Thakur

Reputation: 3895

You need to provide the service in your dialog component as well.

@Component({
  selector: 'my-dialog',
  providers: [ MyService ],
  template: `<div>Today's lottery number is {{service.lotteryNumber}}.</div>`,
})
export class DialogComponent {
  constructor(private service: MyService) { }
}

Please have a look at the changed plunker:https://plnkr.co/edit/feYrKfG1CfW785mDERCv?p=preview

Upvotes: 0

Related Questions