Created
June 25, 2016 08:39
-
-
Save sonicoder86/f377d9d4026f33ded21e03db5fdcb3a3 to your computer and use it in GitHub Desktop.
Authentication in Angular 2 - part 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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