2

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?

1

If getTasks is global, you can just remove 'this', i.e.

getTasks();

should work. Typescript will give you an error because it doesn't know where getTasks is defined, but the resulting JavaScript will still work.

Of course, if you're using Typescript, you don't want to ignore the error. You can get around that the cheap way:

((any)window).getTasks();

which will work and won't cause an error in compilation, and it's generally just telling TypeScript to trust you and temporarily suspending type safety.

Another option is to explicitly tell TypeScript that there is a global called getTasks. You can do that by creating your own .d.ts file that defines getTasks, or you can declare it in your code right above where you're going to use it, like so:

interface getTasksInterface{
    ():any;
}

declare var getTasks: getTasksInterface;

Which is just a declaration that there is a global function called getTasks, which takes no arguments, and could return anything. And then you can go back to where we started, which was:

getTasks();

which will work, and won't throw an error during compilation, and doesn't suspend type safety (except by returning any in the declaration).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.