Ms office Word加载项-如何读取自定义文档属性

Ms office Word加载项-如何读取自定义文档属性,ms-office,office365,office-js,office-addins,Ms Office,Office365,Office Js,Office Addins,我正在使用OfficeJSAPI开发一个Word插件 目前,我可以通过执行以下操作向Word文档添加自定义属性: context.document.properties.load(); context.document.properties.customProperties.add("file-name-prop", "my file name"); 如果下载该文件,我可以在压缩的docx中的“custom.xml”文件中看到该属性 但我无法读回财产 我试着这样做: context.docum

我正在使用OfficeJSAPI开发一个Word插件

目前,我可以通过执行以下操作向Word文档添加自定义属性:

context.document.properties.load();
context.document.properties.customProperties.add("file-name-prop", "my file name");
如果下载该文件,我可以在压缩的docx中的“custom.xml”文件中看到该属性

但我无法读回财产

我试着这样做:

context.document.properties.load();
var filenameProp = context.document.properties.customProperties.getItemOrNullObject("file-name-prop");
if (filenameProp) {
    // use filenameProp.value
} else {
    // ignore, property not set
}
执行此操作时,我会遇到以下错误:

code : "PropertyNotLoaded"
message : "The property 'type' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context."
name : "OfficeExtension.Error"
哪种方法是正确的读回属性的方法


(我正在使用此office js:
appsfofice.microsoft.com/lib/beta/hosted/office.js

可能是因为您没有包含部分代码,但我看不到您同步上下文的任何地方。您提供的错误消息表明了相同的情况:“在读取属性的值之前,对包含的对象调用load方法,并对关联的请求上下文调用“context.sync()”。看起来您完全或部分缺少
context.sync()
。同步上下文后,您应该能够获取自定义属性。例如,要创建自定义属性,代码应该类似于

function getProperties() { 
    Word.run(function (context) {
        var customDocProps = context.document.properties.customProperties;
        context.load(customDocProps);
        return context.sync()
            .then(function () {
                console.log(customDocProps.items.length);
             })
     })
}
函数setProperty(属性名称、属性值){
运行(函数(上下文){
context.document.properties.customProperties.add(属性名称、属性值);
返回context.sync()
.catch(函数(e){
控制台日志(e.message);
})
})
}
当您需要获取属性时,代码仍然使用“sync”使属性可用。例如,要获取自定义属性,代码应该类似于

function getProperties() { 
    Word.run(function (context) {
        var customDocProps = context.document.properties.customProperties;
        context.load(customDocProps);
        return context.sync()
            .then(function () {
                console.log(customDocProps.items.length);
             })
     })
}

Slava的答案是正确的,但要真正读取属性值,我还必须实际加载该属性值,我发现它非常复杂,但是

最终工作代码(借用斯拉瓦的样本):


您的回答是正确的,但为了实际读取属性值,我还必须使上下文“加载”实际属性。我将此作为一个单独的答案发布,以供将来参考。单个属性只需要一次同步