【问题标题】:Add array into an array of object in angular typescript将数组添加到角度打字稿中的对象数组中
【发布时间】:2019-10-19 22:41:46
【问题描述】:

我正在尝试将一个字符串数组推送到一个对象数组中 --> Accessright[];

selectedAccessRights: String[];
accessRights: Accessright[];


for (var i = 0; i < this.numOfPages; i++) {
  this.selectedAccessRights.push(this.selectedPages[i].entityName);
  //I have tried to the following as well, but it doesn't add everything to the accessRights object. Only the last element
  //this.accessRights[i].entityName = this.selectedPages[i].entityName;
}

this.accessRights = this.accessRights.push(this.selectedAccessRights);

但是上面一行给了我一个错误

String[]”类型的参数不能分配给类型参数 'Accessright'。类型“String[]”缺少以下属性 从类型'Accessright':accessRightIdentityNameentityAttribute

还尝试从其他帖子添加和插入,但对我不起作用。

老实说,没有想法,调试了这么久。如果有人可以看一下,将不胜感激。

更新:

38: //Accessright response format
accessGroup: {accessGroupId: 1, accessGroupName: "AdminGroup", accessRights: Array(0), staffs: Array(0)}
accessRightId: 39
entityAttribute: ["charts"]
entityName: "EditDashboard"
__proto__: Object


39: Array(12) //My array
0:
accessRightId: 0
entityName: "Staff"
isDisabled: undefined
1:
accessRightId: 1
entityName: "AccessGroup"
isDisabled: undefined
__proto__: Object

尝试了 any[] 方法,但它不起作用,因为我的 web 服务需要访问权限对象。

【问题讨论】:

  • 请提供Accessright类型的定义。
  • 你能在stackblitz分享你的代码
  • 对我来说,您似乎正在尝试将字符串数组推送到显然不支持它的 Accessright 数组中。您需要修改 AccessRight 的定义,或者将变量类型设为 any,
  • @KiranMistry 很快就会尝试这样做
  • @Mason,你需要在推送之前初始化一个数组selectedAccessRights: String[]=[]=[] 否则数组为空

标签: angular typescript


【解决方案1】:
selectedAccessRights: string;
accessRights: any = [];

   for (var i = 0; i < this.numOfPages; i++) {

       this.selectedAccessRights = this.selectedPages[i].entityName;
       this.accessRights = this.accessRights.push(this.selectedAccessRights);

     }

【讨论】:

  • 请用解决方案解释您的代码,这样会更好
【解决方案2】:

array 的 push 方法在 push 完成后返回数组的长度,所以首先它没有返回 string[]。此外,当您在数组中推送一个值时,它会将其添加到该数组中。 所以,改变 this.accessRights = this.accessRights.push(this.selectedAccessRights);

this.accessRights.push(this.selectedAccessRights);

推送方式的详细说明请参考以下链接 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

【讨论】:

    【解决方案3】:

    更新:

    我决定改变我的后端来接收字符串元素数组。

    这比尝试将字符串数组插入对象然后将其发送到后端要容易得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 2018-04-26
      • 2019-01-29
      • 1970-01-01
      • 2020-06-21
      • 2018-11-06
      • 2018-06-10
      • 1970-01-01
      相关资源
      最近更新 更多