【问题标题】:Angular error : Cannot set property of undefined角度错误:无法设置未定义的属性
【发布时间】:2021-06-14 16:35:20
【问题描述】:

我正在从 API 获取数据到我的 Angular 组件文件,但是当我将数据分配给我的对象变量时,它给了我无法设置未定义属性的错误。 这是我的代码:

类:UserDetails as

export class UserDetails {
    DOB?: string;
    Gender?: string;
    CellPhone?: string;
}

组件.ts:

export class PerComponent implements OnInit {

  public userProfileData: UserDetails;
  constructor( private commonService : CommonService) { 
    
    
  }
  ngOnInit(): void {
    this.loadData();
  }

  loadData() {
    let profileDetailParam = {ProcedureName: 'myprocname', Parameters: ['myparam']};
    this.commonService.GetDataFromStoredProcedure(profileDetailParam)
      .subscribe((data) => {
        let parseString = require('xml2js').parseString;
        let jsonData: UserDetails[];
        parseString(data, function (err, result) {
          if (result.NewDataSet != null)
            jsonData = result.NewDataSet.SPGetDetails[0];
          this.userProfileData = jsonData  ;
          console.log(this.userProfileData);
        });
      });
  }
}

jsondata 包含我期望的 JSON 格式的数据。

我收到错误 core.js:4197 ERROR TypeError: Cannot set property 'userProfileData' of undefined

我知道我没有初始化 userProfileDetails,而是应该如何以及在哪里完成。

我在构造函数和 ngOnInit 中尝试过,但没有任何效果

【问题讨论】:

  • 为什么要将 json 分配给对象?

标签: angular typescript


【解决方案1】:

“this”对象的引用已在函数内部更改

parseString(data, function (err, result) {

要访问外部范围的“this”对象,您可以使用箭头函数:

parseString(data, (err, result) => {
          if (result.NewDataSet != null)
            jsonData = result.NewDataSet.SPGetDetails[0];
          outerContext.userProfileData = jsonData  ;//////// use here
          console.log(outerContext.userProfileData);
        });

您可以在这里阅读更多内容:Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

【讨论】:

    【解决方案2】:

    函数“parseString”存在于“this”之外,因此当您要求它分配该值时,它不知道该上下文中的“this”是什么。

    也许将 parseString 定义为该组件中的自己的函数,并使用“this.parseString”调用它。

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2018-08-10
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多