Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: pass functions to service inside an object

Tags:

angular

I have a component where i pass what i want to display inside a modal like this :

  openConfirmModal() {
    this.service.openmodal(
      {
        buttons: [ {name: 'Close'} ]
      }
    );
  }

The modal service is like this :

  openmodal(input: String) {
    const dialogRef = this.dialog.open(popupComponent, {
      data: new ModalConfirmData({
        buttons: Object.values(data)[0]
      })
    });
  }

Inside my popupComponent i have :

export class ModalPopupData {
  actions: Array<Object>;

  constructor(input?) {
    if (input) {
      this.buttons = input.buttons;
    }
  }
}

Now everything works fine with this, but what i want to do right now is to pass a function to my service in order for it to consume it. Something like this but i don't know how :

{
  function: (modalComponent) => {
    modalComponent.close();
  }
}
like image 707
brxnzaz Avatar asked Jan 26 '23 10:01

brxnzaz


2 Answers

Your callback is expecting to take in a modalComponent as a parameter, but your html is doing nothing of the sort at just (click)="act.callback".

In your current code, you're constructing a method that looks, essentially, like this:

var myCallback = function(modalComponent) {
  modalComponent.close();
}
// ...
var someObj = {
  name: "Close",
  callback: myCallback
}

And so calling it, something would eventually need to do:

// ...
var modalComp = getComponent(); // however it gets hold of a modalComponent
someObj.callback(modalComp);

The method needs to be given a modalComponent to work on, but when calling it, you are not giving it one - in your current code.

So, either your current calling of the callback needs to give the modal you want to close as the input (akin to the comment by @ConnorsFan, assuming this is the relevant reference to the modal), or you change your method to already know about the modal.

var myModal = ...;
var myObj = {
  name: "Close",
  callback: () => { myModal.close(); }
}

Now usage just looks like this, as there is no input params:

myObj.callback();

Anonymous functions are useful for cheekily making use of resources that don't really exist in the caller's scope.

like image 86
Krenom Avatar answered Mar 24 '23 12:03

Krenom


Just like your buttons, you can pass your methods/callbacks to your service and then call them from within the service, e.g.

openConfirmModal() {
  this.service.openmodal({
    buttons: [ {name: 'Close'} ],
    methods: {
      onClose: () => {/** your function body goes here */},
      onSubmit: () => {/** your function body goes here*/}
      .
      .
      .
    }
  });
}

And then in your service, you can call them whenever you like.

Check this also click

like image 25
Usman Saeed Avatar answered Mar 24 '23 12:03

Usman Saeed