简体   繁体   English

如何在 Angular 2 模板中获取 localStorage 值

[英]How to get localStorage value in Angular 2 template

Here is my code,这是我的代码,

HTML: 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>

File component.ts:文件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)
    )

Every comment can switch liked or disliked independently, but I have to use localStorage to decide what status should display.每条评论都可以独立切换喜欢或不喜欢,但我必须使用 localStorage 来决定应该显示什么状态。 Maybe like:也许像:

*ngIf="localStorage.getItem(comment._Id) == 'liked'"

Unfortunately, it's the wrong syntax.不幸的是,这是错误的语法。 I find the getter working on my other case, and the reference is from Angular2 How to display localStorage value inside HTML5 template?我发现 getter 正在处理我的另一个案例,参考来自Angular2 How to display localStorage value inside HTML5 template? . .

In this case, I have no idea to do that, because I can't use get commentLike() in my function, neither use a global variable.在这种情况下,我不知道这样做,因为我不能在我的函数中使用 get commentLike(),也不能使用全局变量。 How do I solve it?我该如何解决?

When you are trying to use *ngIf="localStorage.getItem(comment._Id) == 'liked'" it's trying to find this.localStorage in component.ts, but it doesn't exist, so it's throwing an error... Things like localStorage is common to use wherever required so keep it in global.ts which can be accessed easily...当您尝试使用*ngIf="localStorage.getItem(comment._Id) == 'liked'"它会尝试在 component.ts 中找到 this.localStorage,但它不存在,因此会引发错误.. . 像 localStorage 这样的东西在任何需要的地方都很常见,所以把它保存在 global.ts 中,可以很容易地访问......

In your global.ts , add a function like this:在您的global.ts ,添加如下函数:

export class GlobalApp {

constructor() {}

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

Now update your component.ts :现在更新你的component.ts

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

export class MyComponent {

constructor (public app: GlobalApp)  {
  }
}

Now it's ready to easily use in any template as we have a global declared function:现在它已经准备好在任何模板中轻松使用,因为我们有一个全局声明的函数:

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

It is not the correct way to use localStorage like localStorage[commentId] .这不是像localStorage[commentId]这样使用 localStorage 的正确方法。 You should check it here: Window.localStorage .你应该在这里检查: Window.localStorage

You should use setItem and getItem.您应该使用 setItem 和 getItem。

For your case, I suggest you to use module marcj/angular2-localstorage .对于您的情况,我建议您使用模块marcj/angular2-localstorage

In component:在组件中:

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

In your template:在您的模板中:

*ngIf="comments[index]._id == 'liked'"
@Component({
 selector:'app-any',
 templates:`<div *ngIf="localStorageAlice.getItem('key')">...</div>`
})
export class MyComponent {

 localStorageAlice = localStorage; 
 // to access localStorage in html use localStorageAlice.getItem('key');
}

Alternatively you can use like this或者你可以像这样使用

In your component:在您的组件中:

*ngIf="getItem(comment._Id) == 'liked'"

In your template:在您的模板中:

getItem ( item ) { 
       return localStorage.getItem(item)
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM