حفظ المعلومات في الـ LocalStorage

 سنتحدث عن حفظ المعلومات في الكوكيز عبر الـ LocalStorage وهي مفيدة جداً لتخزين المعلومات مؤقتاً في الصفحة إلى أن يتم إفراغ الذاكرة عبر الكود أو بشكل يدوي:


حفظ البيانات بصيغة JSON

  public setLastMatchItem(Match: any) {
    console.log(this.match);
    localStorage.setItem('LastMatch', JSON.stringify(Match));
  }



لحفظ الكائنات بشكل احترافي نستخدم الصيغة أدناه (دالتي الضبط والحصول):

  getLastMatchItem(): any {
    return JSON.parse(localStorage.getItem('LastMatch'));
  }

  public setLastMatchItem(Match: any) {
    console.log(this.match);
    localStorage.setItem('LastMatch', JSON.stringify(Match));
  }


دالة التشغيل عند البداية (كمثال):

ngOnInit(): void {
    console.log(this.getLastMatchItem())
    this.lastMatch = this.getLastMatchItem();

    if (this.lastMatch.homeTeamName != null) {
      this.match = this.lastMatch;
    }

    this.total = this.match.endTime;
    //------------------------
    this.countDown = timer(0, 1000).subscribe((count) => {
      if (this.match.counter == 59) {
        this.match.startTime++;
        this.match.counter = 0;
      }
      if (this.match.eventStart == true) {
        if (this.match.endTime !== this.match.startTime)
          this.match.counter++;
      }
    });
  }


لحفظ المتغيرات البسيطة بهذه الطريقة:

  getLastAccordionItem(): any {
    return Number(localStorage.getItem('panelId'));
  }

  public setLastAccordionItem(value: string) {
    localStorage.setItem('panelId', value);
  }









تعليقات

المشاركات الشائعة من هذه المدونة

ngx-extended-pdf-viewer

how to getting access token for https://fcm.googleapis.com/v1/projects/al-ayahya-co/messages:send for angular and backend nestjs

طريقة تفعيل زر Inline Keyboard في Telegram Bot