'Hide nav menu when on login page in ANGULAR
I have a routing module that has a LoginComponent on the login page I want to hide the <app-nav-menu></app-nav-menu>
when not logged in. I have tried to subscribe to new BehaviorSubject<boolean>(false);
however when I do this the boolean always seams to be false even when I login.
app-routing.module.ts
const contractModule = () => import('./contract/contract.module').then(x => x.ContractModule);
const routes: Routes = [
{ path: '', component: LoginComponent, pathMatch: 'full' },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'news/:newsId', component: NewsDetailsComponent },
{ path: 'news-manager', component: NewsManagerComponent },
//... MORE PATHS ...
// otherwise redirect to login
{ path: '**', redirectTo: '' }
];
app.component.html
<body>
<app-nav-menu *ngIf="isLoggedIn"></app-nav-menu>
<div class="ml-3 mr-3">
<router-outlet></router-outlet>
</div>
</body>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
isLoggedIn = this.auth.loggedIn; //Should set isLoggedIn Property
title = 'app';
}
employee.service.ts
@Injectable({
providedIn: 'root'
})
export class UserService {
public loggedIn = new BehaviorSubject<boolean>(false); // {1}
public employees: Employee[];
baseUrl = environment.baseUrl;
constructor(private fb: FormBuilder, private http: HttpClient) { }
}
login(formData) {
return this.http.post(this.baseUrl + "employees/login", formData);
}
changePassword(formData) {
return this.http.put(this.baseUrl + "employees/ChangePassword", formData);
}
}
login.component.ts
onSubmit(form: NgForm) {
console.log("Login clicked");
this.userService.login(form.value).subscribe(
(res: any) => {
localStorage.setItem('token', res.token);
this.userService.loggedIn.next(true); //Set loggin to true
this.router.navigateByUrl('/home');
},
err => {
if (err.status == 200) {
this.toastr.info('Change password.', 'New account.')
}
else if (err.status == 401) {
this.toastr.error('Incorrect username or password', 'Authentication failed.');
}
else {
console.log(err);
}
}
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|