2017-07-20 86 views
1

我试着把一个对象转换成一个对象数组如下(我想用这种方式来更新使用Angular4 UI):推对象到一个对象数组则变得不确定对象的每个属性 - 打字稿

CampgroundService.ts

export class CampgroundDetail { 
    campground: Campground; 
    comments: Comment[]; 
} 

CampgroundDetailComponent.ts

@Component({ 
    selector: 'campDetail', 
    templateUrl: './app/components/campgrounds/campground.detail.component.html', 
    styleUrls: ['./app/components/campgrounds/campgrounds.component.css'] 
}) 

export class CampgroundDetailComponent { 
    campDetail: CampgroundDetail = new CampgroundDetail(); 

    updateUI(comment: Comment) { 
     console.log(comment); 

     this.campDetail.comments.push(
     { 
      id: comment.id, 
      text: comment.text, 
      campground_id: comment.campground_id, 
      username: comment.username, 
      user_id: comment.user_id 
     }); 

     console.log(this.campDetail.comments); 
    } 
} 

campground.detail.component.html

<app-comment *ngIf="userdata" [comment]="selectedComment" (insertedComment)="updateUI($event)"></app-comment> 

CommentFormComponent.ts

@Component({ 
    selector: 'app-comment', 
    templateUrl: './app/components/campgrounds/comment.form.component.html', 
    styleUrls: ['./app/components/campgrounds/campgrounds.component.css'] 
}) 

export class CommentFormComponent { 
    @Output() insertedComment = new EventEmitter<Comment>(); 

    doSubmit() { 
     this.comment.user_id = this.userdata.id; 
     this.comment.username = this.userdata.username; 
     this.comment.campground_id = this.campground_id; 

     this.campgroundService.createComment(this.comment) 
      .then(data => { 
       this.campgroundService.getComment(data.comment_id) 
        .then(comment => this.insertedComment.emit(comment)); 
      }).catch(error => { 
      if (error.status === 403) { 
       this.userService.flush(); 
       this.router.navigate(['/login']); 
      } 
     }); 
    } 
} 

根据第一控制台日志,所述comment对象不为空。

enter image description here

然而,推到阵列之后对象的每个属性成为undefined

the value is undefined

我试图在谷歌尽可能多的搜索,但我仍然无法找到任何解决方案。我错过了什么?如果有人会给我任何建议,我将不胜感激。

+0

你如何将'comment'对象传递给'updateUI'? 'comment'可能只是一个没有任何属性的空对象。 – Saravana

+0

嗨,评论对象不是空的(我更新了屏幕截图)。 – Laurence

+0

你如何将它传递给'updateUI'?发布,以及。它涉及什么异步? – Saravana

回答

0

我终于找到了解决方案。我修改CampgroundService.ts

export class CampgroundDetail { 
    campground: Campground; 
    comments: any[]; 
} 

和修改CampgroundDetailComponent.ts

@Component({ 
    selector: 'campDetail', 
    templateUrl: './app/components/campgrounds/campground.detail.component.html', 
    styleUrls: ['./app/components/campgrounds/campgrounds.component.css'] 
}) 

export class CampgroundDetailComponent { 
    campDetail: CampgroundDetail = new CampgroundDetail(); 

    updateUI(comment: Comment) { 
     let tempComment = comment['comment']; 
     this.campDetail.comments.push(tempComment); 
    } 
} 

它现在。

相关问题