EDIT:
This might be a more applicable Question to answer for me as it is more useful How can I watch for changes to localStorage in Angular2?
So I have my main app.component with navbar and and a separate login page. what I want is when they are logged in they can see the menu otherwise they can't. What would be great is if I can add a change to localStorage event. This way I can make one menu to dynamically change on localStorage event.
@Component({
selector: 'my-app',
providers: [FORM_PROVIDERS, RoleService, UserService, Login, LoginService],
inputs: ['loggedIn'],
directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES, LoggedInRouterOutlet],
template: `<body>
<div *ngIf="loggedIn === true">
<nav class="navbar navbar-inverse navbar-top" role="navigation">
<div class="container">
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a (click)="logout()">Logout</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
<div class="container">
<router-outlet></router-outlet>
</div>
</body>`
})
export class AppComponent{
loggedIn: boolean;
constructor(public Login: Login){ /*<--This is a component, can I use it in constructor?*/
Login.loggedIn.subscribe((data) => this.onUserChanged(data));
}
onUserChanged(user){
this.loggedIn = true;
console.log(this.loggedIn);
}
logout(){
localStorage.removeItem('jwt');
}
}
My Login.component:
@Component
export class Login{
jwt: any;
username: string;
password: string;
loggedIn: EventEmitter<boolean>;
constructor(public _loginService: LoginService, public router: Router){
this.loggedIn = new EventEmitter();
}
submitLogin(username, password){
let body = {username, password};
this._loginService.authenticate(body).subscribe(
response => {
localStorage.setItem('jwt', response.json_token);
this.router.navigate(['UserList']);
this.loggedIn.emit(<boolean>true); /*<---Is this in the wrong place?*/
console.log(this.loggedIn);
}
);
}
}
My Login.service:
@Injectable()
export class LoginService {
constructor(public http: Http) {
}
authenticate(form_body){
return this.http.post('/login', JSON.stringify(form_body), {headers: headers})
.map((response => response.json()));
}
}
I am sure it is something wrong with my event emitter. I tried to replicate what was already answered in this post Angular2 - 'watch' provider property in multiple components but I just cannot seem to figure out what I am doing wrong.
I'd like something that says if localstorage is set show menu. Thanks!