0

is there any way to store the data created/edited in localstorage using json format where should i write the localstorage? in edit component or the main component where the function of getAllNotes() called

And mostly what is the use of this localstorage and sessionstorage?

.ts file export class NotesListComponent implements OnInit {

  public subscribe:Subscription;
  public notes:Notes[] = [];
  public inputText:string = '';

  constructor(private noteService:NotesService, private route:ActivatedRoute, private router:Router) { }

  ngOnInit() {
    this.subscribe = this.noteService.notesChangeInDOM.subscribe(
      (data:Notes[])=>{
        this.notes = data
      }
    )
  this.notes = this.noteService.getAllNotes()
  }

  onAddNewNote(){
    this.router.navigate(['newNote'],{relativeTo:this.route})
  }

  search(){
    if(this.inputText != ''){
      this.notes = this.notes.filter(res=>{
        return (res.name.toLocaleLowerCase().match(this.inputText.toLocaleLowerCase()) )
      })
    }else if(this.inputText == ''){
      this.ngOnInit()
    }
  }


}

service.ts

import { Injectable } from '@angular/core';
import { Notes } from '../models/noteModel';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class NotesService {

  public notesChangeInDOM = new Subject<Notes[]>();

  private notes: Notes[] = [
    new Notes(
      'This Notes is related to the thing Dummy Content',
      new Date(2019,2,11,9,25,0),
      new Date(2019,2,11,9,25,0)
    ),
    new Notes(
      'The time that sun rises and sets is the most beautiful scene',
      new Date(2019,2,11,18,25,0),
      new Date(2019,2,11,18,25,0)
    ),
    new Notes(
      'The documents has to be uploaded to the cliets before the deadline',
      new Date(),
      new Date()
    ),
    new Notes(
      'Meeting has to be scheduled by this week',
      new Date(),
      new Date()
    ),
  ];


  constructor() { }


  setNotes(note:Notes[]){
    this.notes = note
  }

  getAllNotes(){
     return this.notes.slice()
  }

  getNoteById(id:number){
    return this.notes[id]
  }

  addNewNote(note:Notes){
    this.notes.push(note)
    return this.notesChangeInDOM.next(this.notes.slice())
  }

  editNote(id:number, note:Notes){
    this.notes[id] = note
    return this.notesChangeInDOM.next(this.notes.slice())   
  }

  deleteNote(id:number){
    this.notes.splice(id,1)
    return this.notesChangeInDOM.next(this.notes.slice())
  }

}

2 Answers2

0

localStorage vs sessionStorage

localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data. The examples in this post are for localStorage, but the same syntax works for sessionStorage.

Session Storage
This maintains a separate storage area for each given origin that’s available for the duration of the page session.This session will flush when the tabs closed.

Local Storage Store data into client side browser using HTML5, Its supports only all modern browsers.Its same as session storage but persists more than even the browser is closed and reopened.

Creating Entries

Create key/value pair entries with localStorage.setItem, providing a key and a value:

let key = 'Item 1';
localStorage.setItem(key, 'Value');

Reading Entries

Read entries with localStorage.getItem:

let myItem = localStorage.getItem(key);

Updating Entries Update an entry just as you would create a new one with setItem, but with a key that already exists:

localStorage.setItem(key, 'New Value');

Deleting Entries Delete an entry with the removeItem method:

localStorage.removeItem(key);

Clearing Everything

Here’s how to clear everything that’s stored in localStorage:

localStorage.clear();

Storing Json Objects

Only strings can be stored with localStorage or sessionStorage, but you can use JSON.stringify to store more complex objects and JSON.parse to read them:

# Create item:

let myObj = { name: 'Skip', breed: 'Labrador' };
    localStorage.setItem(key, JSON.stringify(myObj));

# Read item:

 let item = JSON.parse(localStorage.getItem(key));

Checking for Items Here’s how you can test for the presence of items in the loclaStorage:

if (localStorage.length > 0) {
  // We have items
} else {
  // No items
}

Checking for Support Test for localStorage support by checking if it’s available on the window object:

if (window.localStorage) {
  // localStorage supported
}

Iterating Over Items

localStorage or sessionStorage don’t have a forEach method, but you can iterate over the items with a good old for loop:

for (let i = 0; i < localStorage.length; i++){
  let key = localStorage.key(i);
  let value = localStorage.getItem(key);
  console.log(key, value);
}
DeC
  • 2,226
  • 22
  • 42
0

Look everything in javascript is object! Yes, there are some predefined APIs which can help you to manage the data in the browser localstorage.

Link : https://blog.logrocket.com/the-complete-guide-to-using-localstorage-in-javascript-apps-ba44edb53a36/

Differnce between local and session seesion storage : What is the difference between localStorage, sessionStorage, session and cookies?

It may help you! :)

Abhishek Gautam
  • 1,617
  • 3
  • 18
  • 29