we will not explore that topic in greater depth. You can refer to the Packt library for further reference.

Now that we know how to handle user login, implementing a user logout() method that literally reverses what the previous login() method did is pretty easy:

app/shared/services/authentication.service.ts

logout(): Promise<boolean> {
  return new Promise(resolve => {
    window.sessionStorage.removeItem('token');
   resolve(true);
  });
}

Our third requirement was to provide a property or method that would tell us if the user is authenticated, so they can proceed to secured pages. Keeping in mind that user permission is tied to the existence or absence of a security token stored in the browser storage layer, the method logic is really simple:

static isAuthorized(): boolean {
  return !!window.sessionStorage.getItem('token');
}

We will discuss this method and the rationale behind its static annotation later on. Now, let’s move into the last bit of our service: providing an Observable that allows UI elements and other application clients to subscribe to updates in the user status. First, we will create a public EventEmitter member, which we can use to send notifications every time the user logs in and out so that other classes and components can subscribe to it as mere observers and react to those events. Obviously, the login and logout methods will be updated to also send the corresponding notifications to the observers depending on the actions taken and the user state at all times.

With all these changes, this is the final layout of our injectable authentication service:

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export default class AuthenticationService {
  userIsloggedIn: EventEmitter<boolean>;

  constructor() {
    this.userIsloggedIn = new EventEmitter();
  }

  login({ username, password }): Promise<boolean> {
    return new Promise(resolve => {
      let validCredentials: boolean = false;

      // @NOTE: In a normal scenario this check
      // should be performed against a web service:
      if (username === '[email protected]' &&
        password === 'letmein') {
        validCredentials = true;
        window.sessionStorage.setItem('token', 'eyJhbGciOi');
      }

      this.userIsloggedIn.emit(validCredentials);
      resolve(validCredentials);
    });
  }

  logout(): Promise<boolean> {
    return new Promise(resolve => {
      window.sessionStorage.removeItem('token');
      this.userIsloggedIn.emit(false);
      resolve(true);
    });
  }

  static isAuthorized(): boolean {
    return !!window.sessionStorage.getItem('token');
  }
}