import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { CookieService } from 'ngx-cookie-service'; import {environment} from '../environments/environment'; import { IdP, AuthInfo } from './types/types.module'; @Injectable({ providedIn: 'root' }) export class IdpService { idps: IdP[]; idps$: BehaviorSubject; selectedIdp: IdP; selectedIdp$: BehaviorSubject; constructor( public http: HttpClient, public cookieService: CookieService, ) { this.initializeDataService(); } private initializeDataService() { if (!this.idps$) { this.idps$ = > new BehaviorSubject(new Array()); } if (!this.selectedIdp$) { this.selectedIdp$ = > new BehaviorSubject(new Object); } this.apiCall(); } private apiCall(): void { // initialize the subject with data this.http.get('/backend/auth/v1/info').subscribe( (info: AuthInfo) => { this.idps = info.idps; this.idps$.next(this.idps); let preferredIdP: IdP = this.idps.find((idp: IdP) => idp.id === this.getIdPPreference()); let defaultIdP: IdP = this.idps.find((idp: IdP) => idp.id === info.default); if (preferredIdP) { this.selectedIdp = preferredIdP; } else if (defaultIdP) { this.selectedIdp = defaultIdP; } else if (this.idps.length > 0) { this.selectedIdp = this.idps[0]; } else { console.log("No IdPs available. Unable to login"); } this.selectedIdp$.next(this.selectedIdp); } ); } private getIdPPreference(): number { return Number(this.cookieService.get(environment.idpCookieName)); } public subscribeIdps(): Observable { return this.idps$.asObservable(); } public subscribeSelectedIdp(): Observable { return this.selectedIdp$.asObservable(); } public setIdPPreference(idp: IdP) { this.cookieService.set(environment.idpCookieName, String(idp.id)); } }