在Angular 8应用程序中实现会话存储 [英] Implement session storage in an Angular 8 application

查看:74
本文介绍了在Angular 8应用程序中实现会话存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a movie application to aid my learning. I will like to know how to capture and save the number of clicks on button in session storage.

我已经能够使点击生效.它增加了,并显示了每个按钮的点击次数,我使用指令进行了此操作.我还尝试将按钮的ID作为键,并将单击的次数作为值附加到会话存储中,我可以看到它在登录时就可以使用,但是每次刷新页面时似乎都不会保留.

I have been able to get the click working. It increases and display number of click on each button, I did this with a directive. I also tried to attached the id of the button as key and number of click as value to session storage and I could see that it works when I logged it but it seem not to remain whenever I refresh the page.

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

NB: I am using an API to fetch my data

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并在每个按钮上都喜欢更新会话存储

I want to be able to access the DOM and have the session storage update likes on each buttons

<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 sessionStorage .无需外部库或导入.在大多数浏览器中,它应该是开箱即用的.

For saving values while refreshing the page, you can use the localStorage or the sessionStorage for that. There is no external library or import necessary. It should work out of the box in most of the browsers.

要保存:

// 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中进行检查.

You can check this in Chrome using the dev tools.

这篇关于在Angular 8应用程序中实现会话存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆