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
對象不爲空。
然而,推到陣列之後對象的每個屬性成爲undefined
。
我試圖在谷歌儘可能多的搜索,但我仍然無法找到任何解決方案。我錯過了什麼?如果有人會給我任何建議,我將不勝感激。
你如何將'comment'對象傳遞給'updateUI'? 'comment'可能只是一個沒有任何屬性的空對象。 – Saravana
嗨,評論對象不是空的(我更新了屏幕截圖)。 – Laurence
你如何將它傳遞給'updateUI'?發佈,以及。它涉及什麼異步? – Saravana