5
votes

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.

2

2 Answers

1
votes

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

1
votes

The Office.js library will not load in a browser, so the Office.initialize() doesn't run. But you can debug the add-in in the Office application with the F12 tool at C:\Windows\SysWOW64\F12\F12Chooser.exe

Update: You can find help for the tool here: https://docs.microsoft.com/en-us/microsoft-edge/f12-devtools-guide