在 Angular 8 应用程序中实现会话存储

2024-04-18

我正在构建一个电影应用程序来帮助我的学习。我想知道如何捕获按钮的点击次数并将其保存在会话存储中。

我已经能够让点击工作了。它增加并显示每个按钮的点击次数,我用指令做到了这一点。我还尝试将按钮的 id 作为键和点击次数作为值附加到会话存储中,我可以看到它在我记录时有效,但每当我刷新页面时它似乎都不会保留。

注意:我正在使用 API 来获取我的数据

登陆页面组件

import { CountClicks } from './counter.directive';
import { HttpService } from './../http.service';
import { Component, OnInit, ElementRef } from "@angular/core";


@Component({
  selector: "app-landing-page",
  templateUrl: "./landing.component.html",
  styleUrls: ["./landing.component.scss"]
})
export class LandingPageComponent implements OnInit {
  constructor(private _http: HttpService, private elRef:ElementRef) {}
  movies: Object;
  title = "CORNFLIX";
  ids:any;
  storage:any;
  public likeCounter: number = 0;
  ngOnInit() {
    this._http.getMovies().subscribe(data => {
      this.movies = data;
      // for (let x of data['results']){
      //   if(sessionStorage.getItem('#'+x.id) != null){
      //     console.log("#" + x.id);
      //     this.ids = sessionStorage.getItem("#" + x.id);
      //     console.log(this.ids);
      //   }

      // }
      // console.log(this.ids);
    });
    this.storage = sessionStorage
    console.log(this.storage)
  }

增加点赞数的指令

import { Directive, HostListener } from "@angular/core";

@Directive({ selector: "a[counting]" })


export class CountClicks {
  numberOfClicks = 1;
  number:any
  store:any;
  getValue:any;
  
  
  @HostListener("click", ["$event.target"])
  onClick(a): void {
    
    a.innerHTML = `Likes ${this.numberOfClicks++}`;
    this.number = this.numberOfClicks+1
    // console.log(localStorage.getItem(a.id));
    if(sessionStorage.getItem(a.id)){
        this.number = sessionStorage.getItem(a.id);
        // sessionStorage.clear()
    }
    this.store = sessionStorage.setItem(a.id, a.innerHTML);
    this.getValue = sessionStorage.getItem(a.id)
    a.innerHTML = this.getValue;
    // console.log("button", btn.id, "number of clicks:", this.numberOfClicks++);
  }
}

我希望能够访问 DOM 并在每个按钮上更新会话存储

<section class="jumbotron">
    <h2>
       Welcome to {{title}}
    </h2>

</section>

<div *ngIf="movies" class="container-fluid d-flex p-2 bd-highlight mb-3 flex-wrap  justify-content-between">
    
    <div *ngFor = "let movie of movies['results']" class="card d-block mb-3 " style="width: 18rem;">
        <img src='https://image.tmdb.org/t/p/w500{{movie.poster_path}}' class="card-img-top" alt="Movie image">
        <div  class="card-body">
            <h5  class="card-title">Title: {{movie.title}}</h5>
            <p class="card-text">Year: {{movie.release_date.slice(0, 4)}}</p>
            <a href="#/" class="btn btn-color" id={{movie.id}}>More details</a>
            <a href="#/"   class="btn btn-color" #{{likeCounter}} id=#{{movie.id}} counting>Likes</a>
        </div>
    </div>
</div> 

要在刷新页面时保存值,您可以使用localStorage or the sessionStorage为了那个原因。无需外部库或导入。它应该可以在大多数浏览器中开箱即用。

用于保存:

// clicks is the variable containing your value to save
localStorage.setItem('clickCounter', clicks);
// If you want to use the sessionStorage
// sessionStorage.setItem('clickCounter', clicks);

用于加载:

const clicks = localStorage.getItem('clickCounter');
// If you want to use the sessionStorage
// const clicks = sessionStorage.getItem('clickCounter');

您可以使用开发工具在 Chrome 中检查这一点。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Angular 8 应用程序中实现会话存储 的相关文章

随机推荐