Let’s Make a Tiny Gradebook with Angular2: Local Storage

source code

Local Storage!

If you recall from part 1 of this series, I didn’t want to make a backend. But I still want to save, so I used the local storage object. Don’t know what local storage is? Go here.

All familiar now with what it is? Awesome, let’s get to using it. I could simply use the localStorage api in any of my components, but what if someday I decided to replace the local storage with a backend of some sort? I mean, I won’t, but what if I did… Think of the possibilities! So let’s do this is quasi smart way by making a service.  

What’s a service? It’s basically a file that houses functions. Now that’s one dumbed down description! But it’ll do for now. Let’s look at my service… in a strictly platonic way of course.

I’m skimping on a lot here that I’m sure will annoy me later, but this is a functional service that utilizes the browser’s local storage.

  • To save, I pass in the name of the object and its data. It then gets put into another object called ‘tinyGrades’ which is then saved to the local storage. 
  • To get data, I pass in the name of the object I want. 

The nice thing about this is that I could replace this with a REST service and only have minimal-ish refactoring. 

Next I added the serviced to the top level component.

You can add the service in the main.ts file where you do call the bootstrap function like so

But the angular2 team discourages this. Instead you’ll want to place it in the top-level component. Doing it here means that any child component, which will be every component I make, will get access to a single instance of the service. 

Moving on. You can see I’m also using the service to check if a user has logged in already. If not, on to the login page they go. Otherwise, they are sent to the dashboard.

Finally, my login component grabs the localStorageService from it’s parent. *Remember that by having the top level component inject it as a provider, all of its child component have access to it. And what do you know? The login component is one of those child components. Almost like I planned it. So let’s take a little peek at it.

After all is said and done, I ended up with a service that saves and retrieves data from the local storage!

local storage

My saved data! Woot!

But what about sessionStorage? Honestly I didn’t want to login constantly, so I wanted to keep the data around hence, local storage 

Wrap-up

  • local storage
  • Services
  • Funny cat photo

Wait, I forgot the funny cat photo!

red-wine-cat

Stay cool cat

Thanks for reading!

Facebooktwittergoogle_plusredditpinterestlinkedinby feather