Skip to content

Instantly share code, notes, and snippets.

@sonicoder86
Created June 25, 2016 08:39
Show Gist options
  • Save sonicoder86/f377d9d4026f33ded21e03db5fdcb3a3 to your computer and use it in GitHub Desktop.
Save sonicoder86/f377d9d4026f33ded21e03db5fdcb3a3 to your computer and use it in GitHub Desktop.
Authentication in Angular 2 - part 2
// user.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import localStorage from 'localStorage';
@Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: Http) {
this.loggedIn = !!localStorage.getItem('auth_token');
}
login(email, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
'/login',
JSON.stringify({ email, password }),
{ headers }
)
.map(res => res.json())
.map((res) => {
if (res.success) {
localStorage.setItem('auth_token', res.auth_token);
this.loggedIn = true;
}
return res.success;
});
}
logout() {
localStorage.removeItem('auth_token');
this.loggedIn = false;
}
isLoggedIn() {
return this.loggedIn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment