Day 5

  • Local Storage Service
  • Session Storage Service
  • Managing tokens with Session Storage

Great! So how do we make a service?

First, cd into the folder you want it in (services.)

Creating a service with Angular CLI


                $ ng g service localStorageService
            
Hint: If you want to change where the service is required, you must change that manually.
  • Take five minutes and generate two new services in your services folder: one for Local Storage and one for Session Storage.
  • Now that you've got those services, let's rewrite our UserService to store our user in Local Storage when we log in.

From this...


                login(user: any) {
                    return this.api.post('/userLogin', user).subscribe((res: any) => {
                      console.log(res);
                      this.router.navigateByUrl('/');
                    });
                  }
            

To this...


                login(user: any) {
                    return this.api.post('/userLogin', user).subscribe((res: any) => {
                      this.localStorage.set('currentUser', res.user);
                    }, err => console.log(err), () => this.router.navigateByUrl('/'));
                  }
            

How could we handle logging our user out?