【问题标题】:Angular TypeError: Cannot read property 'map' of undefined with @Input decoratorAngular TypeError:无法使用@Input 装饰器读取未定义的属性“地图”
【发布时间】:2020-10-16 04:48:44
【问题描述】:

我有一个通过 @Input() 装饰器接收数据的子组件。我的目标是使用来自父组件数据的数组创建一个新对象。我收到了数据,但由于某种原因我不能对这些数据使用map() 方法,这是我的 TS 组件部分:

import { Component, OnInit, Input } from '@angular/core';

import {Group} from "@models/group.model";

@Component({
  selector: 'app-group-admins',
  templateUrl: './group-admins.component.html',
  styleUrls: ['./group-admins.component.css']
})
export class GroupAdminsComponent implements OnInit {
  admins: Array<Group> = [];
  new_admins = []
  @Input('group')
  set _group(value) {
    this.admins = value;
    this.new_admins = value.users.map(a => ({id: a.user, permissions: a.permissions}));
  }
  constructor() { }

  ngOnInit() {
    this.new_admins = this.admins.users.map(a => ({id: a.user, permissions: a.permissions}));
  }
}

和组模型仅供参考:

import {GroupUser} from "@models/group-user.model";

export class Group {
  id: string;
  group_name: string;
  type: string;
  avatar?: string;
  header?: string;
  address?: string;
  date?: string;
  city?: string;
  about?: string;
  verify_status?: string;
  site?: string;
  phone?: string;
  email?: string;
  web_site?: string;
  industry?: true;
  directions_list?: string;
  users: Array<GroupUser>
}

我也不能在 ngOnInit 部分做到这一点。我确定我从@Input() 收到数据,因为我可以console.log 它,任何帮助将不胜感激。

【问题讨论】:

  • 您确实在接收数据,否则会显示cannot read property 'users' of undefined。你应该检查users是否真的设置在你收到的数据中

标签: angular


【解决方案1】:

您确实在接收数据,否则会显示cannot read property 'users' of undefined。您应该检查您收到的数据中是否真的设置了users。此外,admins 字段的类型设置为Array&lt;Group&gt;,但在@Input() 中,您似乎只期望Group 对象,而不是数组,即使您确实将其分配给this.admins

所以有两种可能

  1. .users 属性未在您绑定到组件的group 中设置
  2. group 输入接收一个数组,而usersArray 上不存在,因此会出错。

对于这两种情况,您都必须查看,但很可能您不想将一组组传递给组件,而只是一个组,这意味着您应该查看父模板来修复它

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 2022-01-14
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多