I have an authentication service that makes the authenticated variable equal to true or false.
checkAuthentication(){
this._authService.getAuthentication()
To keep authenticated
in service and share it between components you can use
BehaviorSubject, it's value
to check authentication in different places, and it's subscribe()
method to react on change...
class AuthService {
public authenticated = new BehaviorSubject(null);
getAuthentication() {
this._http.get('/authenticate')
.map(response => response.json())
.map(json => Boolean(json)) // or whatever check you need...
.subscribe((value: boolean) => this.authenticated.next(value))
}
}
class Component {
constuctor(private _authService: AuthService) {
// Only check once even if component is
// destroyed and constructed again
if (this._authService.authenticated.value === null)
this._authService.getAuthentication();
}
onSubmit(){
if (!this._authService.authenticated.value)
throw new Error("You are authenticated!")
}
}
How do I execute a function when
this.authenticated
has changed value?
this._authService.authenticated
.subscribe((value: boolean) => console.log(value))