I have a simple Angular.io application. (angular-cli / 4.1.0)
I have a NavbarComponent that displays a username.
When I access the application for the first time, when I am not registered, and my application is redirected to LoginComponent. My NavBar is also displayed, but without a username. After successfully logging in, I am redirected to my HomeComponent.
And here is the problem. My NavBar does not show username. But if I do an update / ctrl + r, the username will be shown.
What's wrong?
app.component.html
<nav-bar></nav-bar> <router-outlet></router-outlet>
navbar.compoment.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'nav-bar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit { me; ngOnInit() { this.me = JSON.parse(localStorage.getItem('currentUser')); } }
login.component.ts
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { AlertService, AuthenticationService } from '../_services/index'; @Component({ moduleId: module.id, templateUrl: 'login.component.html' }) export class LoginComponent implements OnInit { model: any = {}; loading = false; returnUrl: string; constructor( private route: ActivatedRoute, private router: Router, private authenticationService: AuthenticationService, private alertService: AlertService) { } ngOnInit() { // reset login status this.authenticationService.logout(); // get return url from route parameters or default to '/' this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; } login() { this.loading = true; this.authenticationService.login(this.model.email, this.model.password) .subscribe( data => { this.router.navigate([this.returnUrl]); }, error => { this.alertService.error(error); this.loading = false; this.errorMsg = 'Bad username or password';console.error('An error occurred', error); }); } }
source share