-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathuser.service.ts
78 lines (60 loc) · 2.42 KB
/
user.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { UserRegistration } from '../models/user.registration.interface';
import { ConfigService } from '../utils/config.service';
import {BaseService} from "./base.service";
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx';
//import * as _ from 'lodash';
// Add the RxJS Observable operators we need in this app.
import '../../rxjs-operators';
@Injectable()
export class UserService extends BaseService {
baseUrl: string = '';
// Observable navItem source
private _authNavStatusSource = new BehaviorSubject<boolean>(false);
// Observable navItem stream
authNavStatus$ = this._authNavStatusSource.asObservable();
private loggedIn = false;
constructor(private http: Http, private configService: ConfigService) {
super();
this.loggedIn = !!localStorage.getItem('auth_token');
// ?? not sure if this the best way to broadcast the status but seems to resolve issue on page refresh where auth status is lost in
// header component resulting in authed user nav links disappearing despite the fact user is still logged in
this._authNavStatusSource.next(this.loggedIn);
this.baseUrl = configService.getApiURI();
}
register(email: string, password: string, firstName: string, lastName: string,location: string): Observable<UserRegistration> {
let body = JSON.stringify({ email, password, firstName, lastName,location });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.baseUrl + "/accounts", body, options)
.map(res => true)
.catch(this.handleError);
}
login(userName, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
this.baseUrl + '/auth/login',
JSON.stringify({ userName, password }),{ headers }
)
.map(res => res.json())
.map(res => {
localStorage.setItem('auth_token', res.auth_token);
this.loggedIn = true;
this._authNavStatusSource.next(true);
return true;
})
.catch(this.handleError);
}
logout() {
localStorage.removeItem('auth_token');
this.loggedIn = false;
this._authNavStatusSource.next(false);
}
isLoggedIn() {
return this.loggedIn;
}
}