-1

I have this code in an Angular2 Microsoft Office Add-in project that displays an Office Dialog using the Javascript API.

Office.context.ui.displayDialogAsync(url, {height: 34, width: 20, displayInIframe: true},function (asyncResult) {
  if (asyncResult.status !== Office.AsyncResultStatus.Succeeded) {
    // TODO: Handle error.
    return;
  }

  // Get the dialog and register event handlers.
  dialog = asyncResult.value;

  dialog.addEventHandler(Office.EventType.DialogMessageReceived, function (asyncResult) {
    if (asyncResult.type !== Office.EventType.DialogMessageReceived) {
      return;
    }
    this.router.navigate(['/user'],1);
    dialog.close();
  });
});

And I get this error:

TypeError: this.router is undefined

Where the router is defined in the component constructor.

constructor( private route: ActivatedRoute,
private router: Router,
private location: Location) { }

So the question is, how can I use that router inside the DialogEvenentHandler callback function to navigate to that URL?

cyr_x
  • 13,987
  • 2
  • 32
  • 46
  • It looks like your constructor declares the router as type Router but does not actually assign it a Router object. So it's expected that it would be undefined. – Rick Kirkham Mar 05 '18 at 05:37
  • How should I declare it? – user3403959 Mar 05 '18 at 12:48
  • I'm not an Angular expert, but since Router begins with a capital letter, I presume that it is a class so you can use the "new" operator to create a Router object. – Rick Kirkham Mar 05 '18 at 17:07
  • The Router get's injected by the angular DI system, so everything is fine with his constructor. – cyr_x Mar 05 '18 at 21:45

1 Answers1

1

The problem is that you're not using arrow functions for your handlers and your this context gets lost.

Change your handlers to arrow functions and everything should work just fine.

Office.context.ui.displayDialogAsync(url, {height: 34, width: 20, displayInIframe: true}, asyncResult => {
  // ...
  dialog.addEventHandler(Office.EventType.DialogMessageReceived, asyncResult => {
    // ...
  });
});
cyr_x
  • 13,987
  • 2
  • 32
  • 46