Hi I am using the new alpha component router of angularjs2 https://angular.io/docs/ts/latest/guide/router.html
I have a modal that authenticate a user then creates a JWT in localstorage which holds the user's needed info.
My problem is that if the user is looking on the /home
path there are stuff there that only visible to logged-in users, but after he log in through the modal he has to refresh the page so the components will refresh and show the correct logged-in information
Is there a way to tell angular2 to refresh all the components on the current path? like a page reload but without really reloading the whole page (I dont want to just hit the refresh button for the user)
Thanks in advance
EDIT: maybe there is a feature to FORCE REDIRECT when I try to redirect into a route I am already in?
EDIT2: Trying with observables
@Injectable()
export class UserService {
private loggedInObservable;
constructor(private http: Http) {
this.loggedInObservable = Observable.of(this.checkIsLoggedIn());
}
checkIsLoggedIn() {
let isLoggedIn = false;
try {
isLoggedIn = tokenNotExpired();
} catch(e) {
}
console.log('returning:', isLoggedIn);
return isLoggedIn;
}
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.loggedInObservable.map((val) => console.log('HELLO?'));
});
}
isLoggedInObservable() {
return this.loggedInObservable;
}
}
the map does NOTHING at all (the 'HELLO?' isn't being displayed), although the observer has a value the map function does not call anything.
Using the observer:
import {Component, OnInit, OnDestroy} from '@angular/core';
import {UserService} from '../../services/userservice';
@Component({
selector: 'test-thing',
template: require('./test-thing.html'),
styles: [require('./test-thing.scss')],
providers: [],
directives: [],
pipes: []
})
export class TestThing implements OnInit, OnDestroy{
private isLoggedIn = false;
private sub: any;
constructor(private userService: UserService) {
};
ngOnInit() {
this.sub = this.userService.isLoggedInObservable().subscribe(loggedIn => {
this.isLoggedIn = loggedIn;
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
The initial value is working as intended but when I try to change the value after a successful login (with map) nothing happens, nothing at all.
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
And this is how I use it in a component:
This setup works perfectly for my needs.