Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Office Add-in: "Cannot find name 'Office'"

I created a new Angular project using the angular-cli and then installed the Office TS definitions via npm and put the Office JS API CDN in the header of my index.html. However, in my main.ts, when I call Office.initialize = function(){}; it can’t find the name ‘Office’ even though the namespace is recognized by TS. Does someone know what I'm doing wrong? Thanks!

I've been following the tips page here: https://dev.office.com/docs/add-ins/develop/add-ins-with-angular2

If you want to reproduce my scenario and have Angular CLI installed:

ng new test
cd test
npm install –save-dev @types/office-js

Then open your project directory and go to src/index.html. Add this CDN in the header:

<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>

Then go to src/main.ts

And change it so that the app doesn’t bootstrap the module until it initializes Office:

Office.initialize = function(){
  if (environment.production) {
    enableProdMode();
  }
  platformBrowserDynamic().bootstrapModule(AppModule);
};

UPDATE

I was able to get this to work in my main.ts by using:

declare const Office: any;

Office.initialize = function () {
  platformBrowserDynamic().bootstrapModule(AppModule);
};

However, this only works if the add-in is side-loaded in an Office application. The module doesn't seem to get bootstrapped in the browser and just says 'Loading...'. Is there a way to get it to load in the browser for debugging purposes? I'm concerning about how this will affect debugging and any E2E or unit tests with protractor, karma and jasmine.

like image 643
codex Avatar asked Oct 30 '22 07:10

codex


1 Answers

I recommend you take a look at Script Lab, a recently-announced tool and also open-source showcase sample, that uses Angular 4, and which you can use for inspiration. Some of the underlying technology is also discussed in a podcast about the project.

What we did for Script Lab is we create a Promise for Office.js initialization, and optimistically wait for it for a few seconds. In case we don't receive it, we show a set of buttons to help the user choose whether to launch in web mode or to launch as if it's still within an add-in (and hope for the best).

See also How to correctly check the host: Office, Office online and web browser

like image 79
Michael Zlatkovsky - Microsoft Avatar answered Nov 11 '22 11:11

Michael Zlatkovsky - Microsoft