Office JS getOo xml Пример выдаёт смутную ошибку - PullRequest
2 голосов
/ 01 апреля 2020

Я пытаюсь запустить этот точный пример кода для метода range.getOoxml, подробный здесь из приложения TypeScript React, загруженного как дополнение Word.

пример . js (пример кода из Word Office JS Docs)

// Run a batch operation against the Word object model.
Word.run(function (context) {

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    var range = context.document.getSelection();

    // Queue a command to get the OOXML of the current selection.
    var ooxml = range.getOoxml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(function () {
        console.log('The OOXML read from the document was:  ' + ooxml.value);
    });
})
.catch(function (error) {
    console.log('Error: ' + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
        console.log('Debug info: ' + JSON.stringify(error.debugInfo));
    }
});

Запуск этого кода приводит к следующим ошибкам, которые слишком расплывчаты, чтобы я не знал, что с ними делать.

errors.log

Error: {"name":"RichApi.Error","code":"GeneralException","traceMessages":[],"innerError":null,"debugInfo":{"code":"GeneralException","message":"GeneralException","errorLocation":"Range.getOoxml","statement":"selection.getOoxml();","surroundingStatements":["var root=context.root;","var selection=root.getSelection();","// Instantiate {selection}","// >>>>>","selection.getOoxml();","// <<<<<"],"fullStatements":["var root=context.root;","var selection=root.getSelection();","// Instantiate {selection}","selection.getOoxml();"]},"line":24,"column":243848,"sourceURL":"https://appsforoffice.microsoft.com/lib/1.1/hosted/word-mac-16.00.js"}
instrument.js:110

Debug info: {"code":"GeneralException","message":"GeneralException","errorLocation":"Range.getOoxml","statement":"selection.getOoxml();","surroundingStatements":["var root=context.root;","var selection=root.getSelection();","// Instantiate {selection}","// >>>>>","selection.getOoxml();","// <<<<<"],"fullStatements":["var root=context.root;","var selection=root.getSelection();","// Instantiate {selection}","selection.getOoxml();"]}
instrument.js:110

Что не так? Как я могу заставить это работать?

То же самое работало в моей кодовой базе не слишком долго go, когда я создал этот SO ответ , но теперь ни тот, ни другой пример кода не работают.

so-answer.ts (связанный ответный пост)

Word.run(async (context: RequestContext) => {
  const range: Range = context.document.getSelection();
  const ooxml: ClientResult<string> = range.getOoxml();
  context.load(range);
  await context.sync();

  const ooxmlVal = ooxml.value;
  if (ooxmlVal) {

    const lowered = ooxmlVal.toLowerCase();
    const isChart = lowered.includes("excel") && lowered.includes("chart");
    if (isChart) {
      console.log("CURSOR IS ON CHART");
    }
  }
});

Это приводит к следующей ошибке:

Unhandled Promise Rejection: RichApi.Error: GeneralException
instrument.js:110

Опять супер расплывчато, совершенно бесполезно , Так что теперь я просто засоряю фрагмент с context.sync() вызовами, завернутыми в try/catch s, в последний раз, чтобы заставить это работать, и это выглядит так:

littered.ts

    Word.run(async (context: RequestContext) => {
        try {
            await context.sync();
        } catch (e) {
            console.log(e);
        }

        const range: Word.Range = context.document.getSelection();
        try {
            await context.sync();
        } catch (e) {
            console.log(e);
        }

        const ooxml: ClientResult<string> = range.getOoxml();
        context.load(range);

        try {
            await context.sync();
        } catch (e) {
            console.log(e);
        }

        const ooxmlVal = ooxml.value;
        if (ooxmlVal) {

            const lowered = ooxmlVal.toLowerCase();
            const isChart = lowered.includes("excel") && lowered.includes("chart");
            if (isChart) {
                console.log("CURSOR IS ON CHART");
            }
        }
    });

Возвращает:

littered.logs

[Log] GeneralException: GeneralException (app.618b84ff7477d6aeb4f7.js, line 225089)
[Error] Unhandled Promise Rejection: RichApi.Error: The value of the result object has not been loaded yet. Before reading the value property, call "context.sync()" on the associated request context.
    (anonymous function) (word-mac-16.00.js:24:309999)
    promiseReactionJob
[Log] GeneralException: GeneralException (app.618b84ff7477d6aeb4f7.js, line 225089)
[Error] Unhandled Promise Rejection: RichApi.Error: The value of the result object has not been loaded yet. Before reading the value property, call "context.sync()" on the associated request context.
    (anonymous function) (word-mac-16.00.js:24:309999)
    promiseReactionJob

Что мне с этим делать?!

РЕДАКТИРОВАТЬ

ДАЛЕЕ, я выполнил своего рода проверку работоспособности, создав совершенно новый проект Office / Word с генератором Yeoman и просто добавил фрагмент примера из Документы Word для обработчика кликов. Когда он запускается, он получает ТОЧНЫЕ ОДНОВРЕМЕННЫЕ ОШИБКИ.

Это доказывает, что это не определено c мой проект / репо.

Вы можете проверить это самостоятельно с репо здесь

РЕДАКТИРОВАТЬ 2

Я провел тестирование для Ma c и Windows, и это, похоже, ошибка, появившаяся в недавнем обновлении версии , Теперь я перешел к повторному открытию проблемы, которая, кажется, решает эту проблему, но была закрыта для бездействия от первоначального создателя проблемы. Вы можете отслеживать это по приведенному ниже адресу:

https://github.com/OfficeDev/office-js/issues/998#issuecomment -607394484

Так как команда Office JS официально еще не объявила об ошибке, я буду оставьте этот пост открытым пока.

РЕДАКТИРОВАТЬ 3

Office JS команда до сих пор не открыла ветку вопросов, на которую я ссылался, поэтому я создал новую один здесь: https://github.com/OfficeDev/office-js/issues/1097.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...