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

Dar*_*een 12 session-storage typescript angular

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

我已经能够让点击工作。它增加并显示每个按钮的点击次数,我用一个指令做到了这一点。我还尝试将按钮的 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)
  }
Run Code Online (Sandbox Code Playgroud)

增加喜欢的指令

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++);
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够访问 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> 
Run Code Online (Sandbox Code Playgroud)

Lin*_* Vu 16

要在刷新页面时保存值,您可以使用localStoragesessionStorage。不需要外部库或导入。它应该在大多数浏览器中开箱即用。

为了节省:

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

装载:

const clicks = localStorage.getItem('clickCounter');
// If you want to use the sessionStorage
// const clicks = sessionStorage.getItem('clickCounter');
Run Code Online (Sandbox Code Playgroud)

您可以使用开发工具在 Chrome 中进行检查。

在此处输入图片说明


gan*_*045 14

您可以使用会话存储或本地存储来临时存储数据。

Session storage将可用于特定选项卡,我们可以Local storage在浏览器中使用。两者默认为同源,我们也可以使用键值对手动存储值(值必须是字符串)。

关闭浏览器的选项卡(会话)后,该选项卡上的会话存储将被清除,如果本地存储,我们需要明确清除它。最大存储限制分别为 5MB 和 10MB。

我们可以像下面这样保存和检索数据,

保存:

sessionStorage.setItem('id', noOfClicks);   // localStorage.setItem('id', noOfClicks);

sessionStorage.setItem('userDetails', JSON.stringify(userDetails));   // if it's object
Run Code Online (Sandbox Code Playgroud)

要得到

sessionStorage.getItem('id');    // localStorage.getItem('id');

User user = JSON.parse(sessionStorage.getItem("userDetails")) as User;  // if it's object
Run Code Online (Sandbox Code Playgroud)

修改:

sessionStorage.removeItem('id');    // localStorage.removeItem('id');

sessionStorage.clear();   // localStorage.clear();
Run Code Online (Sandbox Code Playgroud)

PS: getItem()也将数据作为字符串返回,如果它是对象,我们需要将其转换为JSON格式才能访问。

您可以在此处阅读有关浏览器存储的更多信息。

  1. localStorage、sessionStorage 和 cookie 的区别

  2. 本地存储与会话存储