import { HttpClient } from '@angular/common/http' ; import { Injectable } from '@angular/core' ; import { BehaviorSubject , Observable } from 'rxjs' ; import { catchError } from 'rxjs/operators' ; import { environment } from '../../../environments/environment' ; import { AuthService , IAuthStatus } from '../../auth/auth.service' ; import { CacheService } from '../../auth/cache.service' ; import { transformError } from '../../common/common' ; import { IUser , User } from './user' ; export interface IUsers { items : IUser [ ] ; total : number ; } export interface IUserService { currentUser : BehaviorSubject < IUser > ; getCurrentUser ( ) : Observable < IUser > ; getUser ( id ) : Observable < IUser > ; updateUser ( user ) : Observable < IUser > ; getUsers ( pageSize , searchText , pagesToSkip ) : Observable < IUsers > ; } @ Injectable ( { providedIn : 'root' , } ) export class UserService extends CacheService implements IUserService { currentUser = new BehaviorSubject < IUser > ( this . getItem ( 'user' ) || new User ( ) ) ; private currentAuthStatus : IAuthStatus ; constructor ( private httpClient , private authService ) { super ( ) ; this . currentUser . subscribe ( user => this . setItem ( 'user' , user ) ) ; this . authService . authStatus . subscribe ( authStatus => ( this . currentAuthStatus = authStatus ) ) ; } getCurrentUser ( ) { const userObservable = this . getUser ( this . currentAuthStatus . userId ) . pipe ( catchError ( transformError ) ) ; userObservable . subscribe ( user => this . currentUser . next ( user ) , err => Observable . throw ( err ) ) ; return userObservable ; } getUser ( id ) { return this . httpClient . get < IUser > ( `${ environment . baseUrl }/v1/user/${ id }` ) ; } updateUser ( user ) { this . setItem ( 'draft-user' , user ) ; const updateResponse = this . httpClient . put < IUser > ( `${ environment . baseUrl }/v1/user/${ user . id || 0 }` , user ) . pipe ( catchError ( transformError ) ) ; updateResponse . subscribe ( res => { this . currentUser . next ( res ) ; this . removeItem ( 'draft-user' ) ; } , err => Observable . throw ( err ) ) ; return updateResponse ; } getUsers ( pageSize , searchText = '' , pagesToSkip = 0 ) { return this . httpClient . get < IUsers > ( `${ environment . baseUrl }/v1/users` , { params : { search : searchText , offset : pagesToSkip . toString ( ) , limit : pageSize . toString ( ) , } , } ) ; } }