如何将对象放入另一个对象Angular / Javascript

时间:2016-07-05 07:54:01

标签: javascript arrays angularjs angular ionic2

我正在制作一款应用,并且在尝试将阵列推入另一个阵列时我陷入了困境。 我收到错误"无法读取属性'推送'未定义的。"

这是对象:

export var CARDS: any[] = [
     {
        channel: "facebook"
        date: "2016-01-07"
        comments: [
            { 
               content: "Hey would you look at this card?",
               user: "John Appleseed",
               avatar: "url"
            },
            { 
               content: "I like this card!",
               user: "John Doe",
               avatar: "url"
            }
        ]
     },
     {
        channel: "facebook"
        date: "2016-01-07"
        comments: [
            { 
               content: "Hey would you look at this card?",
               user: "Jane Doe",
               avatar: "url"
            }
        ]
    }];

我的应用中有一个选项可以为卡片添加评论。因此我创建了:

newComment = {
    content: "",
    user: "",
    avatar: ""
  };

使用按钮我调用submitComment函数:

submitComment(comment) {
    console.log(this.newComment);
    this.comment.push(newComment);
}

我的HTML看起来像这样(fyi:我正在使用离子,这解释了离子输入)

 <ion-input type="text" placeholder="Type a comment..."  [(ngModel)]="newComment.content"></ion-input> 
 <button (click)="submitComment(comment)">Send comment</button>

我在submitComment函数中做了一个console.log,它显示了正确的信息。但这种推动并不奏效。我收到错误&#39;无法读取属性&#39;推送&#39;未定义的。我试过了#34; this.newComment&#34;括号之间,但它也不起作用。

我刚刚开始了解Angular / JS,所以它可能很简单,我无法理解。在此先感谢您的帮助: - )

编辑:我忘了添加。我做了一个* ngFor =&#34;让card.comments评论&#34;显示评论。因此我只使用&#34;评论&#34;进一步的HTML。

2 个答案:

答案 0 :(得分:3)

您的问题是因为您为comment方法提供的submitComment变量为空。因此,您无法在其上调用任何方法(特别是push)......

否则您的CARDS属性似乎无法正确定义。您可以这样定义:

CARDS: any [] = [
  {
    channel: "facebook"
    date: "2016-01-07"
    comments: [
      { 
        content: "Hey would you look at this card?",
        user: "John Appleseed",
        avatar: "url"
      },
      { 
        content: "I like this card!",
        user: "John Doe",
        avatar: "url"
      }
    ]
  },
  {
    channel: "facebook"
    date: "2016-01-07"
    comments: [
      { 
        content: "Hey would you look at this card?",
        user: "Jane Doe",
        avatar: "url"
      }
    ]
  }
];

答案 1 :(得分:0)

感谢蒂埃里,我解决了我的问题。 :-) 我在代码中查看了一些小东西。这是解决方案,适用于遇到同样问题的每个人。

我的问题在于我使用点击功能提供的值。我第一次

(click)="submitComment(comment)"

但是评论&#39;未定义。我以为我的ngFor =&#34;让card.comments评论&#34;会定义它,但我的点击功能在ngFor之外。因此我必须创建

(click)="submitComment(card)"

在我的打字稿文件中有以下内容:

 submitComment(card) {
    console.log(this.newComment);
    card.comments.push(this.newComment);
  }