Ok so seems what I needed is a BehaviorSubject since you can push values into it,subscribe to it to get changes and it projects the last value it got the first time you subscribe to it which is exactly what I need.
My code is now as follows:
userservice.ts
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {serverPost} from '../../functions';
import {BehaviorSubject} from 'rxjs/BehaviorSubject'
import {tokenNotExpired} from 'angular2-jwt';
@Injectable()
export class UserService {
private isLoggedInSubject: BehaviorSubject<boolean>;
constructor(private http: Http) {
this.isLoggedInSubject = new BehaviorSubject(this.checkIsLoggedIn());
}
isLoggedInObserver() {
return this.isLoggedInSubject;
}
checkIsLoggedIn() {
let isLoggedIn = false;
try {
isLoggedIn = tokenNotExpired();
} catch(e) {
}
return isLoggedIn;
}
signUp(model, cbSuccess=null, cbError=null, cbAlways=null) {
serverPost(this, '/api/users', model, cbSuccess, cbError, cbAlways, (data)=> {
localStorage.setItem("id_token", data.id_token);
this.isLoggedInSubject.next(this.checkIsLoggedIn());
});
}
login(model, cbSuccess=null, cbError=null, cbAlways=null) {
serverPost(this, '/api/users/login', model, cbSuccess, cbError, cbAlways, (data)=> {
localStorage.setItem("id_token", data.id_token);
this.isLoggedInSubject.next(this.checkIsLoggedIn());
});
}
}
And this is how I use it in a component:
export class TestComponent implements OnInit, OnDestroy{
private isLoggedIn = false;
private loginSub;
constructor(private userService: UserService) {
};
ngOnInit() {
this.loginSub = this.userService.isLoggedInObserver().subscribe(val => {
this.isLoggedIn = val;
});
}
ngOnDestroy() {
this.loginSub.unsubscribe();
}
}
This setup works perfectly for my needs.