File

src/app/services/authentication.service.ts

Index

Properties
Methods
Accessors

Constructor

constructor(http: HttpClient, spinner: NgxSpinnerService, toastr: ToastrService)
Parameters :
Name Type Optional
http HttpClient No
spinner NgxSpinnerService No
toastr ToastrService No

Methods

login
login(username, password)
Parameters :
Name Optional
username No
password No
Returns : any
logout
logout()
Returns : void

Properties

Public currentUser
Type : Observable<User>
Private currentUserSubject
Type : BehaviorSubject<User>

Accessors

currentUserValue
getcurrentUserValue()
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { User } from '../models/user';
import { environment } from '../../environments/environment';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    private currentUserSubject: BehaviorSubject<User>;
    public currentUser: Observable<User>;

    constructor(private http: HttpClient, private spinner: NgxSpinnerService, private toastr: ToastrService) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
    }

    public get currentUserValue(): User {
        return this.currentUserSubject.value;
    }

    login(username, password) {
        return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password })
            .pipe(map(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
                this.currentUserSubject.next(user);
                return user;
            }));
    }

    logout() {
        // remove user from local storage and set current user to null
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
        // tslint:disable-next-line: quotemark
        this.toastr.success("Logout sucessfully");
    }
}

results matching ""

    No results matching ""