首页 > 解决方案 > Office Word Addin:在办公环境中调用 Angular 6 服务时出现空值或未定义错误

问题描述

我正在使用 Angular 6 开发 word officejs 应用程序。在 Office.context.document 中调用 this.anyservice 或 this.anyvariable 时出错。

服务是,

 @Injectable()
    
          export class OfficeService {
    
    constructor(private ngxXml2jsonService: NgxXml2jsonService) {
    }
    
    
    
    ReadData(){
    
       Office.context.document.customXmlParts.getByNamespaceAsync("namespace", function (asyncResult) {
    
          this.ngxXml2jsonService = asyncResult
    
       });
    
     }
    
    }

我将结果 Office.context.document 分配给 this.ngxml2jsonService。

出现错误: 无法设置未定义或空引用的属性“ngxml2jsonService”

即使我试图调用另一个服务,但仍然得到同样的错误。然后我打印console.log(this),所以才知道“this”在office.context.document中也无法访问。

我需要帮助来解决这个问题。

标签: angular

解决方案


在调用 office.context 方法之前,您需要在其他变量中维护此实例...

像这样的东西:

ReadData() {
  var self = this;
  Office.context.document.customXmlParts.getByNamespaceAsync("namespace", function (asyncResult) {
      self.ngxXml2jsonService = asyncResult
  });
}

这是必需的,因为 getByNamespaceAsync 将调用您的 callback() 函数。


推荐阅读