Randy
Randy

Reputation: 9809

How do I inject objects from the DI container in Aurelia-dialog

Using Aurelia, you can put stuff in the container and then inject it. The container state is not shared in the dialog.

Is there a way to get the data I injected in the container, and use it inside the dialog?


Code example

home.js

fetchString(){
  this.data = JSON.parse(stringform);
  this.container.registerInstance('tpscform', this.data);
}

custom-element.js

import {DialogService} from 'aurelia-dialog';
import {LookupFieldsDialog} from './dialog/lookup-fields-dialog';

@inject('tpscform', DialogService)
export class LookupFieldsQuestion {

  constructor(form, dialog){
    console.log(form); // returns the object from the container - works
    //...
  }

  submit() {
    this.dialogService.open({
      viewModel: LookupFieldsDialog,
      model: this.question,
      lock: false
    });
  }

}

lookup-fields-dialog.js

import {inject} from 'aurelia-framework';
import {DialogController} from 'aurelia-dialog';

@inject(DialogController, 'tpscform')
export class LookupFieldsDialog {

  constructor(controller, form) {
    this.controller = controller;
    console.log(form); // Returns the string 'tpscform' - doesn't work
  }

  activate(question) {
    this.question = question;
  }

}

Upvotes: 2

Views: 566

Answers (1)

Randy
Randy

Reputation: 9809

As @FabioLuz mentioned, you can pass the container into the dialog:

import {Container} from 'aurelia-framework';
import {DialogService} from 'aurelia-dialog';
import {LookupFieldsDialog} from './dialog/lookup-fields-dialog';

@inject(DialogService, Container)
export class LookupFieldsQuestion {

  constructor(dialogService, container) {
    this.container = container;
    this.dialogService = dialogService;
  }

  submit() {
    this.dialogService.open({
      viewModel: LookupFieldsDialog,
      model: this.question,

      // Share current container here
      childContainer: this.container.createChild(),

      lock: false
    });
  }

Upvotes: 1

Related Questions