0

Using TypeScript and Angular, I have created a function named getTasks() that I want to fire when a modal is closed. This is the function:

getTasks() {
 this.http.get(`https://example.com/_api/web/lists/getbytitle('Tasks')/items`).subscribe(data => {
  console.log(data['value'])
  this.tasks = data['value']
 })
}

I can successfully create my modal with the following:

newTask() {
  var options = {
    url: `https://example.com/divisions/dev/lists/Tasks/NewForm.aspx?itemParent=${this.itemID}`,
    dialogReturnValueCallback: Function['createDelegate'](null, this.newTaskClosed)
  }
  window.parent['SP'].UI.ModalDialog.showModalDialog(options);
}

This is my callback function that successfully logs when the modal has been closed:

newTaskClosed(result, value) {
  console.log(result, value)
  this.getTasks(); // Thinks that 'this' is null
}

Running this gives me the following error:

Uncaught TypeError: Cannot read property 'getTasks' of null

How can I solve this?

cfoster5
  • 1,696
  • 5
  • 28
  • 42

2 Answers2

1

I didn't get the error when I test in my environment.

enter image description here

Test demo:

private newTask= (): void =>{
    var options = {
      url: this.props.context.pageContext.web.absoluteUrl+`/lists/ParentA/NewForm.aspx`,
      dialogReturnValueCallback: Function['createDelegate'](null, this.newTaskClosed)
    }    
    window.parent['SP'].UI.ModalDialog.showModalDialog(options);
  }
  private newTaskClosed= (result, value): void => {
    console.log(result, value);    
    this.getTasks(); // Thinks that 'this' is null
  }
  private getTasks= (): void => {
    alert('getTasks function')
   }

In Render function, call the dialog.

return (     
      <div >  
        <Button text="NewTask" onClick={this.newTask} />
Lee
  • 5,305
  • 1
  • 6
  • 12
0

I solved this by using this answer as a starting point. By using an arrow function for the dialogReturnValueCallback property, I was able to keep the correct context of this. I also had success with referencing this.getTasks() through a variable that binds this.

Changing the options object to:

let options = {
  url: `https://portal.oldnational.com/divisions/it/iDemand/lists/Tasks/NewForm.aspx?itemParent=${this.itemID}`,
  dialogReturnValueCallback: () => this.getTasks()
}

or by using

let boundFunction = (function() {
  this.getTasks();
}).bind(this);

let options = {
  url: `https://portal.oldnational.com/divisions/it/iDemand/lists/Tasks/NewForm.aspx?itemParent=${this.itemID}`,
  dialogReturnValueCallback: boundFunction
}

worked for me.

cfoster5
  • 1,696
  • 5
  • 28
  • 42