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

时间:2019-10-22 09:14:29

标签: angular typescript session-storage

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

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

NB:我正在使用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> 

3 个答案:

答案 0 :(得分:2)

要在刷新页面时保存值,可以使用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中进行检查。

enter image description here

答案 1 :(得分:0)

您可以将数据存储如下。

详细了解浏览器存储here

保存数据

sessionStorage.setItem('id', noOfClicks);

获取数据

sessionStorage.getItem(id');

答案 2 :(得分:0)

您可以使用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;

    }