I've created a authentication service which components can subscribe to permission changes (login/logout/role change ,etc). In isAuthenticated function, I'm returning a subject. The problem is that I want to return the subject with a value (like Observable.of. For now, I'm using setTimeout.
@Injectable()
export class AuthenticationService {
constructor(private credentials: CredantialsStorageService,
private oauthService:OAuth2Service,
private secureHttp: SecureHttpService) {}
private isAuthenticatedSubject: Subject<boolean> = new Subject<boolean>();
login(email:string, password: string, remember?:boolean ): Observable<boolean> {
return this.oauthService.login(email, password)
.flatMap(() => this.getAndStoreUserCredantials())
.map((userCredantials: any) => {
this.isAuthenticatedSubject.next(true);
return true;
})
}
logout(): Observable<void> {
return this.secureHttp.post('/logout', null)
.finally(() => {
this.credentials.clear();
this.oauthService.clear();
this.isAuthenticatedSubject.next(false);
})
.map(() => null);
}
isAuthenticated(): Observable<boolean> {
setTimeout(() => { //Hack - find a way to change this
this.isAuthenticatedSubject.next(this.oauthService.isAuthenticated());
})
return this.isAuthenticatedSubject;
}
private getAndStoreUserCredantials() {
return this.secureHttp.get('/user/info')
.map((res:Response) => {
let userCredantials = res.json();
this.credentials.set(userCredantials);
return userCredantials;
})
}
}