【发布时间】: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