2017-12-24 15 views
-3

코드에서 볼 수 있듯이 객체 내부에 배열 값을 동적으로 만들려고했으나 디버깅 할 때 문제가 없었지만 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> 
+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 } ]; 

하여 테스트 함수 인수에 선언함으로써 당신이 그것을 숫자와 문자열을 공급하고 만들 수 있습니다 벙어리 따옴표 대신 따옴표 붙이기 :이 코드는 복사 붙여 넣기 오류입니까, 아니면 실제로 코드에 스마트 (및 유효하지 않은) 따옴표를 사용하고 있습니까? – Terry

+0

그건 복사 붙여 넣기 실수 ... –

+0

@ j.doe, 혹시이 문제를 해결 했습니까? – Iancovici

답변

0

가 적절한 형태로 배열을 선언하십시오 : 나를 위해

private newsFeeds : Array<any> = ... 
+0

그것은 작동하지 않습니다 –

0

작품

이 개체가 올바르게 해석되어 있는지 확인합니다. 나는 당신의 작은 따옴표를 대체해야했습니다. 당신은

ngOnInit() { 
    this.postComment(0, 'comment'); 
    console.log(this.newsFeeds); 
    } 


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



    } 

enter image description here

+0

그것은 나를 위해 작동하지 않습니다 .... 사실 입력 상자 keyup.enter 이벤트에이 함수를 호출하고 있습니다, 각도와 typescript 이오니아 3 작업 오전 및 피험자 개발자 오전, 내 작업은 내 이오니아 응용 프로그램에서 페이스 북 스타일 주석 기능을 구현하려면 ... 여기에 HTML 코드의 일부가 있습니다. ngIf = "f.isCommentEnable">

+0

@ j.doe 우리는 당신이 여기에 노출 된 것을 도울 수 있습니다. 물체와 함수가 잘 작동하는 것처럼 보이기 때문에 이것은 먹이를 먹이로 넣는 문제와 분명히 관련이 있습니다. – Iancovici

+0

입력이 올바르다. 푸시 메소드를 호출하기 전에 콘솔 로그를 통해 체크했다. 인덱스와 값의 값은 괜찮지 만 푸시에서 오류가 발생한다.