Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simulation of a login functionality in Angular2, token based.

In this gist I show a simple setup for helping me build the frontend of a backend functionality before programming the latter. In this case it is the login functionality.

On the login page there are three buttons to allow me to login with different credentials, so that I can see what the server would tell me in each case. That will guide me to understand how I want to program the frontend.

A couple of seconds after clicking each button I'll get a response from the server.

  1. the first button will cause an error response, which I show in a feedback field on the login page.
  2. the second and third buttons will cause an OK response, which I store in the auth key of the local storage system.
login works!
<button (click)="login('GrouchoMarx', '')">Login with wrong credentials</button>
<button (click)="login('GrouchoMarx', '123456')">Login as member</button>
<button (click)="login('CharlieChaplin', '567890')">Login as vip</button>
import { Component, OnInit } from '@angular/core';
import { SessionService } from '../session.service';
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
export class LoginComponent implements OnInit {
feedback = "Make your choice.";
private sessionService: SessionService
) { }
ngOnInit() {
login(username, password) { = `Logging in as ${username} with password ${password || '(none)'}...`;
.create({username, password})
token => localStorage.setItem('auth', token),
err => = err
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export class SessionService {
constructor() { }
create(credentials): Observable<string> {
return new Observable(observer => {
setTimeout(() => {
if (credentials.password !== '') {`${credentials.username}-1234567890`);
} else {
observer.error('wrong credentials');
}, 2000);
Copy link

aercolino commented Mar 8, 2017

  1. Notice how I avoid fields altogether at

  2. Notice how I simulate the backend behaviour right into the service at The wrapping timeout is important to have a relevant asynchronous simulation.

  3. Notice how I take control of the login error at The subscribe accepts 3 arguments. The first is for the OK path, the second for the error path, and the third for the completion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment