无法将值推送到对象内的javascript数组中

时间:2017-12-24 16:19:45

标签: angular typescript ionic3

正如你在代码中看到的那样,我试图在一个对象内动态创建数组值,它在调试时没有问题,但是当我尝试在数组中使用push方法时会抛出一个错误。我是在角度为4的Ionic 3上工作。我在输入框的keyup.enter事件中调用该函数。

// this is the object
private newsFeeds=[
{
avatarUrl:’…/assets/fb/avatar.png’,
userName:‘Karim Benzema’,
time:‘16 minutes ago’,
caption:‘Wow!!!’,
imageUrl:‘https://upload.wikimedia.org/wikipedia/commons/e/ec/Ara_ararauna_Luc_Viatour.jpg’,
like:‘Like’,
numberOfLikes:2,
comments:['hello'],
isCommentEnable:false
},
{
avatarUrl:’…/assets/fb/avatar2.png’,
userName:‘Unknown Singh’,
time:‘2 hrs ago’,
caption:‘Pc:Unknown’,
imageUrl:‘https://i.pinimg.com/736x/50/e0/b6/50e0b65efd2d634053d7a8d1cd9d94fc--so-funny-funny-
stuff.jpg’,
like:‘Like’,
numberOfLikes:3,
comments:[],
isCommentEnable:false
}
];

postComment(index,value){
console.log(`${index} : ${value}`); //shows correct index and value
this.newsFeeds[index].comments.push(value); //-->error 
//Throws runtime error ‘comments.push is not a function’
}

我的HTML代码:

<ion-list [virtualScroll]= “newsFeeds”>
<ion-card *virtualItem=“let f; let i=index”>
<span *ngIf=“f.isCommentEnable”>
<input type=“text” [(ngModel)]=“f.comments” (keyup.enter)=“postComment(this.i,item.value);” #item>
</span>
</ion-card>
</ion-list>

2 个答案:

答案 0 :(得分:0)

尝试使用适当的类型声明数组:

msg3

答案 1 :(得分:0)

为我工作

确保正确解释您的对象。我不得不更换你的单引号。您可以按console.log(newsFeeds);

进行测试
  private newsFeeds=[
    {
      avatarUrl:'…/assets/fb/avatar.png',
      userName:'Karim Benzema',
      time:'16 minutes ago',
      caption:'Wow!!!',
      imageUrl:'https://upload.wikimedia.org/wikipedia/commons/e/ec/Ara_ararauna_Luc_Viatour.jpg',
      like:'Like',
      numberOfLikes:2,
      comments:['hello'],
      isCommentEnable:false
  }
];

并确保通过声明函数参数

为数字和字符串提供数据
  ngOnInit() {
    this.postComment(0, 'comment');
    console.log(this.newsFeeds);
  }


  postComment(index: number,value: string){
    this.newsFeeds[index].comments.push(value);



  }

enter image description here