2017-03-09 80 views
2

这里是我的代码,如何获得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(),既不使用全局变量。我如何解决它?

+0

你是否在localstorage中存储你的“注释”? – mickdev

+0

我不明白。你写“我必须使用localStorage来决定应显示的状态”。如果您没有将您的评论存储在本地存储中(并且不更新它们,如果更新),您如何确定哪些评论是喜欢的,哪些不喜欢? 。 – mickdev

+0

对不起,我作出这样的评论的误解是一个数组,和我分开存放在评论每个评论像localStorage.setItem(commentId,“喜欢”(或“不喜欢”)),所以我的localStorage是关键:commentId,值“喜欢“谢谢:) – PaulHuang

回答

4

当你试图使用*ngIf="localStorage.getItem(comment._Id) == 'liked'"它试图找到this.localStorage在component.ts,但它不存在,所以它抛出一个错误...像localStorage这样的事情是常见的使用的地方,所以保持在global.ts可以轻松访问...

在您的global.ts,增加一个功能是这样的:

export class GlobalApp { 

constructor() {} 

public localStorageItem(id: string): string { 
    return localStorage.getItem(id); 
} 

开始更新component.ts

import {GlobalApp} from '../helpers'; 

export class MyComponent { 

constructor (public app: GlobalApp) { 
    } 
} 

现在,它已经准备好很容易地在任何模板中使用,因为我们有一个全球性的声明功能:

*ngIf="app.localStorageItem(comment._Id) == 'liked'" 
+0

谢谢。这正是我需要的! – PaulHuang

0

这是不使用localStorage的像localStorage[commentId]的正确方法。你应该在这里检查它:Window.localStorage

您应该使用setItem和的getItem。

对于你的情况,我建议你使用模块marcj/angular2-localstorage

在组件:

@LocalStorage() public comments:any = []; 

在模板:

*ngIf="comments[index]._id == 'liked'"