首页 > 解决方案 > 使用解析的 json 作为 javascript 对象时出现“未定义”参数错误

问题描述

我的Angular申请收到以下信息json

{isSignedIn: true, additional-info: ""{\"external-profile\":{\"email\":\"manu.chadha@ho…\"firstname\":\"Manu\",\"lastname\":\"Chadha\"}}""}

我将 解析additional-info为类型的对象UserProfileAPI

let resultObject =JSON.parse(subscribed['additional-info']) as UserProfileAPI;

export class UserProfileAPI {
  'external-profile': User;
  constructor(externalProfile:User){
    this['external-profile'] = externalProfile;
  }
}

export class User {
  constructor (public firstname:string,
               public lastname:string,
               public email:string,
               public password:string=""){} 
}

我的component班级有一个变量profile:UserProfileAPI;,我想将收到的值映射jsonprofile.

我已经profile初始化ngOnInit

  this.profile = new UserProfileAPI(new User("","","",""))

但是当我尝试映射json

let resultObject =JSON.parse(subscribed['additional-info']) as UserProfileAPI;
console.log("parsed additional info is ",resultObject);
this.profile["external-profile"].email = resultObject["external-profile"].email;
this.profile["external-profile"].firstname = resultObject["external-profile"].firstname;
this.profile["external-profile"].lastname = resultObject["external-profile"].lastname;

我收到错误ERROR TypeError: Cannot read property 'email' of undefined at SafeSubscriber._next (nav-component.component.ts:91) at

我做错了什么?

标签: javascriptangular6

解决方案


推荐阅读