【问题标题】:Implement session storage in an Angular 8 application在 Angular 8 应用程序中实现会话存储
【发布时间】:2020-02-18 09:41:31
【问题描述】:

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

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

【问题讨论】:

    标签: angular typescript session-storage


    【解决方案1】:

    要在刷新页面时保存值,您可以使用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);
    

    用于加载:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      保存:

      sessionStorage.setItem('id', noOfClicks);   // localStorage.setItem('id', noOfClicks);
      
      sessionStorage.setItem('userDetails', JSON.stringify(userDetails));   // if it's object
      

      获取

      sessionStorage.getItem('id');    // localStorage.getItem('id');
      
      User user = JSON.parse(sessionStorage.getItem("userDetails")) as User;  // if it's object
      

      修改:

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

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

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

      1. Difference between localStorage, sessionStorage and cookies

      2. localstorage-vs-sessionstorage

      【讨论】:

        【解决方案3】:

        你可以使用ngx-webstorage 模块

        首先你必须将它作为一个依赖添加到你的 Angular 项目中

        npm install --save ngx-webstorage
        

        然后在你的主模块中声明这个库,例如

        import {NgModule} from '@angular/core';
        import {BrowserModule} from '@angular/platform-browser';
        import {NgxWebstorageModule} from 'ngx-webstorage';
        
        @NgModule({
            declarations: [...],
            imports: [
                BrowserModule,
                NgxWebstorageModule.forRoot(),
                //NgxWebstorageModule.forRoot({ prefix: 'custom', separator: '.', caseSensitive:true }) 
                // The forRoot method allows to configure the prefix, the separator and the caseSensitive option used by the library
                // Default values:
                // prefix: "ngx-webstorage"
                // separator: "|"
                // caseSensitive: false
            ],
            bootstrap: [...]
        })
        export class AppModule {
        }
        

        最后在组件中注入您想要的服务和/或使用可用的装饰器,例如

        import {Component} from '@angular/core';
        import {LocalStorageService, SessionStorageService} from 'ngx-webstorage';
        
        @Component({
            selector: 'foo',
            template: `foobar`
        })
        
            export class FooComponent {
        
                constructor(private localSt:LocalStorageService) {}
        
                ngOnInit() {
                    this.localSt.observe('key')
                        .subscribe((value) => console.log('new value', value));
                }
        
            }
        
            import {Component} from '@angular/core';
            import {LocalStorage, SessionStorage} from 'ngx-webstorage';
        
            @Component({
                selector: 'foo',
                template: `{{boundValue}}`,
            })
            export class FooComponent {
        
                @LocalStorage()
                public boundValue;
        
            }
        

        【讨论】:

        • 本例中如何获取和设置?
        猜你喜欢
        • 1970-01-01
        • 2016-06-16
        • 2021-06-06
        • 2013-12-23
        • 2020-08-26
        • 2013-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多