这里是我的代码,如何获得localStorage的值角2模板
HTML:
<div *ngFor="let comment of comments | orderBy: '-'+orderBy">
<div class="comment-item">
<div class="row">
<div class="col-md-8">
{{comment.userName}}
</div>
<div class="col-md-4">
<div class="comment-timeago">
{{comment.time | timeAgo}}
</div>
<div class="likedicon">
<i class="fa fa-heart-o disliked" aria-hidden="true" (click)="likeComment(comment._id, comment)"></i>
<i class="fa fa-heart liked" aria-hidden="true" *ngIf="comment.liked == 'liked'" (click)="dislikeComment(comment._id, comment)"></i>
</div>
<div class="like-num">
{{comment.like}}
</div>
</div>
</div>
</div>
</div>
文件component.ts:
likeComment(commentId, comment) {
localStorage[commentId] = "liked";
comment.liked = localStorage[commentId];
comment.like ++;
this.dataService.likeComment(commentId).subscribe(
// Post data to server
error => console.log(error)
)
}
dislikeComment(commentId, comment) {
localStorage[commentId] = "disliked";
comment.liked = localStorage[commentId];
comment.like --;
this.dataService.dislikeComment(commentId).subscribe(
// Post data to server
error => console.log(error)
)
每一个评论可以切换喜欢或不喜欢独立,但我必须使用localStorage来决定应显示的状态。也许喜欢:
*ngIf="localStorage.getItem(comment._Id) == 'liked'"
不幸的是,这是错误的语法。我发现吸气剂工作在我的其他情况下,参考是从Angular2 How to display localStorage value inside HTML5 template?。
在这种情况下,我不知道要做到这一点,因为我不能用我的功能得到commentLike(),既不使用全局变量。我如何解决它?
你是否在localstorage中存储你的“注释”? – mickdev
我不明白。你写“我必须使用localStorage来决定应显示的状态”。如果您没有将您的评论存储在本地存储中(并且不更新它们,如果更新),您如何确定哪些评论是喜欢的,哪些不喜欢? 。 – mickdev
对不起,我作出这样的评论的误解是一个数组,和我分开存放在评论每个评论像localStorage.setItem(commentId,“喜欢”(或“不喜欢”)),所以我的localStorage是关键:commentId,值“喜欢“谢谢:) – PaulHuang