我尝试将对象推送到对象数组中,如下所示(我想用这种方式使用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
。
我尝试尽可能多地搜索谷歌,但我仍然找不到任何解决方案。我错过了什么?如果有人愿意给我任何建议,我将不胜感激。
答案 0 :(得分: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);
}
}
现在有效。