Angular routing including auth guard and redirections - javascript

I have an angular app and want to implement client side routing. I have 3 components: login, chat and admin. Access to admin and chat is restricted by an auth guard. Ideally the routing behavior should be:
click login -> route to login and redirect to admin
click admin or chat -> route to login and redirect on successful login to the clicked on (admin or chat respectlively)
I managed to setup the redirections nearly correct, but the redirection when clicking login still depends on where I clicked before/last. Meaning that if the user clicks on login it will goto login and on successful login it redirects to chat. The user then logs out and clicks login, it goes to login but redirects to chat instead of admin, which I don't want. Clicks on login should always go to admin regardless of which route was active in past.
How can I achieve this?
Thanks.
app.component
<nav>
<ol>
<li><a routerLink="/login">Login</a></li>
<li><a routerLink="/admin">Admin</a></li>
<li><a routerLink="/chat">Chat</a></li>
</ol>
</nav>
<router-outlet></router-outlet>
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
Login component
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
import { HttpClient } from '#angular/common/http';
import {AuthService} from "../auth.service";
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
email: string;
password: string;
loginMessage: string;
loginForm: FormGroup;
constructor(
private http: HttpClient,
) { }
ngOnInit() {
this.loginForm = new FormGroup({
'email': new FormControl(this.email, [
Validators.required,
Validators.email
]),
'password': new FormControl(this.password, [
Validators.required,
Validators.minLength(2)
])
});
console.log('init');
}
logout(): void {
this.authService.loggedIn = false;
}
login(): void {
if (!this.isValidInput()) { return; }
const data = {email: this.email, pass: this.password};
this.authService.login('localhost:3000/login', data).subscribe((response: any) => {
this.loginForm.reset();
this.authService.loggedIn=true;
let redirect = this.authService.redirecturl ? this.router.parseUrl(this.authService.redirecturl) : '/admin';
this.router.navigateByUrl(redirect);
});
}
isValidInput(): Boolean {
if (this.loginForm.valid) {
this.email = this.loginForm.get('email').value;
this.password = this.loginForm.get('password').value;
return true;
}
return false;
}
}
<form [formGroup]="loginForm">
<!-- this div is just for debugging purpose -->
<div id="displayFormValues">
Value: {{loginForm.value | json}}
</div>
<label for="email"><b>Email</b></label>
<input id="email" type="email" formControlName="email" email="true" required>
<label for="password"><b>Password</b></label>
<input id="password" type="password" formControlName="password" required>
<button (click)="login()" routerLink="/admin" routerLinkActive="active">Login</button>
<div id="loginMessage">{{loginMessage}}</div>
</form>
admin component
<p>admin works!</p>
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
chat component
<p>chat works!</p>
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
authgauard
import { Injectable } from '#angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor() {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
if (this.authService.isLoggedIn()) {
return true;
} else {
this.authService.redirecturl = url;
this.router.navigate(['/login']);
return false;
}
}
}
app-routing module
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { ChatComponent } from './chat/chat.component';
import { AdminComponent } from './admin/admin.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{
path: 'login',
component: LoginComponent
},
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard]
},
{
path: 'chat',
component: ChatComponent,
canActivate: [AuthGuard]
}
];
#NgModule({
imports: [RouterModule.forRoot(routes, {enableTracing: true})],
exports: [RouterModule]
})
export class AppRoutingModule { }
auth service
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable({
providedIn: 'root'
})
export class AuthService {
redirecturl: string; // used for redirect after successful login
username: string;
loginMessage: string;
greeting = 'Hello guest!';
loggedIn = false;
config = {
serverHost: 'localhost',
serverPort: 3000,
loginRoute: 'login',
standardGreeting: `Hello guest!`,
standardUsername: 'Guest'
};
constructor(private http: HttpClient) { }
login(loginUrl: any, body: { pass: string }) {
return this.http.post(loginUrl, body, httpOptions)
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError(
'Something bad happened; please try again later.');
}
isLoggedIn(): boolean {
return this.loggedIn;
}
}
}

Instead of doing this <button (click)="login()" routerLink="/admin" routerLinkActive="active">Login</button> in html put redirection url in typescript like this.
login(): void {
if (!this.isValidInput()) { return; }
const data = {email: this.email, pass: this.password};
this.authService.login('localhost:3000/login', data).subscribe((response: any) => {
if(response.isSuccess){
this.loginForm.reset();
this.authService.loggedIn=true;
if(!this.authService.redirectUrl){
this.router.navigateByUrl('/admin');
} else{
this.router.navigateByUrl(this.authService.redirectUrl);
}
}
});
}
and If you are navigating to Login URL then please remove redirectUrl other wise it will always redirect to last visited page.
EDIT
In App.component.html you are navigating to login using routerlink instead of that use this
<nav>
<ol>
<li><a (click)='redirectToLogin()'>Login</a></li>
<li><a routerLink="/admin">Admin</a></li>
<li><a routerLink="/chat">Chat</a></li>
</ol>
</nav>
<router-outlet></router-outlet>
and in app.component.ts use this
redirectToLogin(){
this.authService.redirectUrl = null;
this.router.navigateByUrl('/login');
}

Related

route navigation is not working in angular 9

I am working on a login and home component in my angular app.
Login service is validating the username and password of the user.
After successful login, it should redirect user to the home page.
But router redirect is not working properly.
login component
import { Router } from '#angular/router';
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { User } from 'src/app/shared/models/user';
import { AuthService } from '../services/auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
userName: FormControl;
password: FormControl;
loginFormGroup: FormGroup;
loginError: boolean;
errorMessage: string;
messageString: string;
constructor(private router: Router, private authService: AuthService) { }
ngOnInit() {
this.userName = new FormControl("", [Validators.required]);
this.password = new FormControl("", [Validators.required]);
this.loginFormGroup = new FormGroup({
userName: this.userName,
password: this.password
});
}
login() {
this.loginError = false;
if (this.loginFormGroup.valid) {
let user: User = new User();
user.userId = this.userName.value;
user.password = this.password.value;
this.authService.login(user)
.subscribe(res =>
{
console.log(res)
this.router.navigate(["home"])
console.log("res")
},
error =>
{
console.log(error)
});
}
}
}
and login service
import { Injectable } from "#angular/core";
import { Router } from "#angular/router";
import { Observable } from "rxjs";
import { share } from "rxjs/operators";
import { environment} from 'src/environments/environment';
import { HttpClient, HttpParams, HttpHeaders} from "#angular/common/http";
import { User } from 'src/app/shared/models/user';
#Injectable({ providedIn: "root" })
export class AuthService {
user: User;
resp=401;
get userDetail(): User {
return this.user;
}
constructor(
private router: Router,
private http: HttpClient
) {
}
login(user: User): Observable<any> {
var formData = new FormData();
formData.append("userId", user.userId);
formData.append("password", user.password);
return this.http.get<any>(url+"Validate_Login_User",{
headers: new HttpHeaders(),
params: new HttpParams().set("User_Id","user.userId")
})
}
}
routes
import { NgModule } from "#angular/core";
import { Routes, RouterModule } from "#angular/router";
import { AuthGuard } from "./authentication/services/auth.guard";
import { LoginComponent } from "./authentication/login/login.component";
import { LayoutComponent } from "./shared/components/layout/layout.component";
import { PageNotFoundComponent } from "./shared/components/page.not.found.component";
import { MenuComponent } from './menu/menu.component';
const routes: Routes = [
{ path: "login", component: LoginComponent },
{
path: "home",
component: HomeComponent,
canActivate: [AuthGuard],
children: [
{
//childroutes
},
{
//childroutes
},
],
},
{ path: "**", component: PageNotFoundComponent },
{ path: "Menu", component: MenuComponent}
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {
onSameUrlNavigation: "ignore",
useHash: true,
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
console log in login component
even though the console is printing success, route navigate is not happening and its still in login page
replace your code with the following piece of code, that should work.
this.loginError = false;
if (this.loginFormGroup.valid) {
let user: User = new User();
user.userId = this.userName.value;
user.password = this.password.value;
this.authService.login(user)
.subscribe(res =>
{
console.log(res)
this.router.navigate(["/home"])
console.log("res")
},
error =>
{
console.log(error)
});
}
}
Edited:
Please replace your ngModule with the below code:
#NgModule({
imports: [
RouterModule.forRoot(routes, {
useHash: true,
}),
],
exports: [RouterModule],
})
Try this.
this.router.navigateByUrl('/home');

Image User Firebase

I have created an interface called user with an email property, password and photo url. When I load it in the ngOnInit() the value user (object) photo url says src = (unknown). I want to show the associated image (storage - when I register / create the user) on the header
//user.class.ts
export class User {
email: string;
password: string;
photoUrl: string;
}
//header.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { AngularFireAuth } from '#angular/fire/auth';
import { AuthService } from 'src/app/service/auth.service';
import { User } from 'src/app/share/user.class';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
user: User = new User();
constructor(
private router: Router,
private auth:AngularFireAuth,
private authSvc:AuthService
) { }
ngOnInit() {
this.authSvc.isAuth().subscribe(user => {
if(user) {
this.user.photoUrl = user.photoUrl;
console.log(this.user.photoUrl);
}
})
}
//auth.service.ts
isAuth(user: User) {
return this.auth.authState.pipe(map(user => user));
}
//header.html
<ion-avatar>
<img src="{{user.photoUrl}}" />
</ion-avatar>
I have made a web app with angular and firebase.
fUser is the user from firebase, and User is my interface
import { Component, OnInit } from '#angular/core'
import { AngularFireAuth } from '#angular/fire/auth'
import { Observable } from 'rxjs'
import { first } from 'rxjs/operators'
import { User as fUser } from 'firebase'
import { User } from '#models/User'
#Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
public user$: Observable<fUser> = this.auth.user
public currentUser: User
constructor(
private auth: AngularFireAuth
) { }
ngOnInit() {
this.user$.pipe(first()).toPromise().then(user => {
this.currentUser = user as User
})
}
}

Angular routing - On routing to a child, View updates only on refresh of the page

I am learning routing from the example on angular docs.
The problem is that on clicking an element from crisis list, crisis detail isnt displayed right after click.
If i refresh my screen, then relevant crisis detail is displayed.
So the question is why is the detail visible after refreshing? Whats the solution?
//crisis-center-routing-module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';
import { CrisisListComponent } from './crisis-list/crisis-list.component';
import { CrisisCenterComponent } from './crisis-center/crisis-center.component';
import { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';
const crisisCenterRoutes: Routes = [
{
path: 'crisis-center',
component: CrisisCenterComponent,
children: [
{
path: '',
component: CrisisListComponent,
children: [
{
path: ':id',
component: CrisisDetailComponent
},
{
path: '',
component: CrisisCenterHomeComponent
}
]
}
]
}
];
#NgModule({
imports: [
RouterModule.forChild(crisisCenterRoutes)
],
exports: [
RouterModule
]
})
export class CrisisCenterRoutingModule { }
//crisis-list.component.html
<h2>CRISES</h2>
<ul class="crises">
<li *ngFor="let crisis of crises$ | async" [class.selected]="crisis.id === selectedId">
<a [routerLink]="[crisis.id]">
<span class="badge">{{ crisis.id }}</span>{{ crisis.name }}
</a>
</li>
</ul>
<router-outlet></router-outlet>
//crisis-list-component.ts
import { CrisisService } from '../crisis.service';
import { Crisis } from '../crisis';
import { Component, OnInit } from '#angular/core';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-crisis-list',
templateUrl: './crisis-list.component.html',
styleUrls: ['./crisis-list.component.css']
})
export class CrisisListComponent implements OnInit {
selectedCrisis: Crisis;
crises: Crisis[];
crises$;
selectedId: number;
constructor(private crisisService: CrisisService, private service: CrisisService, private route: ActivatedRoute) { }
ngOnInit() {
this.crises$ = this.route.paramMap.pipe(
switchMap(params => {
this.selectedId = +params.get('id');
return this.service.getCrises();
})
);
}
onSelect(crisis: Crisis): void {
this.selectedCrisis = crisis;
}
getCrises(): void {
this.crisisService.getCrises()
.subscribe((crises) => {
this.crises = crises;
});
}
}
//crisis-detail.component.html
<button (click)='gotoCrises(crisis)'>Back</button>
<div *ngIf="crisis">
<h2>{{crisis.name | uppercase}} Details</h2>
<div><span>id: </span>{{crisis.id}}</div>
<div>
<label>name:
<input [(ngModel)]="crisis.name" placeholder="name" />
</label>
</div>
</div>
//crisis-detail.component.ts
import { Observable } from 'rxjs';
import { CrisisService } from '../crisis.service';
import { Component, OnInit, Input } from '#angular/core';
import { Crisis } from '../crisis';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
import { switchMap } from 'rxjs/operators';
#Component({
selector: 'app-crisis-detail',
templateUrl: './crisis-detail.component.html',
styleUrls: ['./crisis-detail.component.css']
})
export class CrisisDetailComponent implements OnInit {
crisis: Crisis;
private crisis$;
constructor(private route: ActivatedRoute, private router: Router, private service: CrisisService) { }
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
this.crisis$ = this.service.getCrisis(id);
this.crisis$.subscribe((crisis) => {
this.crisis = crisis;
});
}
gotoCrises(crisis: Crisis) {
const crisisId = crisis ? crisis.id : null;
this.router.navigate(['/crisises', { id: crisisId, foo: 'foo' }]);
}
}
The problem was that i was getting id from the url using
activatedRoute.snapshot.paramMap.get('id)
The router-outlet renders the route once. For other clicks in the list, the detail view isnt updated.
In order to constantly listen to changes in id in the url, I had to subscribe to
ActivatedRoute.url
This solution was helpful https://stackoverflow.com/a/47030238/2416260

How to use angular 6 Route Auth Guards for all routes Root and Child Routes?

How to use angular 6 Route Auth Guards for all routes Root and Child Routes ?
1) [ Create guard, the file name would be like auth.guard.ts ]
ng generate guard auth
import { Injectable } from '#angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from
'#angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import {Router} from '#angular/router';
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService,
private myRoute: Router){
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(this.auth.isLoggedIn()){
return true;
}else{
this.myRoute.navigate(["login"]);
return false;
}
}
}
2) Create below pages
ng g c login [Create login page ]
ng g c nav [Create nav page ]
ng g c home [Create home page ]
ng g c registration [Create registration page ]
3) App.module.ts file add below contents
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule,Router,Routes } from '#angular/router';
import { ReactiveFormsModule,FormsModule } from '#angular/forms';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { NavComponent } from './nav/nav.component';
import { HomeComponent } from './home/home.component';
import { RegistrationComponent } from './registration/registration.component';
const myRoots: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' , canActivate:
[AuthGuard]},
{ path: 'register', component: RegistrationComponent },
{ path: 'login', component: LoginComponent},
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];
#NgModule({
declarations: [
AppComponent,
LoginComponent,
NavComponent,
HomeComponent,
RegistrationComponent
],
imports: [
BrowserModule,ReactiveFormsModule,FormsModule,
RouterModule.forRoot(
myRoots,
{ enableTracing: true } // <-- debugging purposes only
)
],
providers: [AuthService,AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
4) Add link in nav.component.html
<p color="primary">
<button routerLink="/home">Home</button>
<button *ngIf="!auth.isLoggedIn()" routerLink="/register">Register</button>
<button *ngIf="!auth.isLoggedIn()" routerLink="/login">Login</button>
<button *ngIf="auth.isLoggedIn()" (click)="auth.logout()">Logout</button>
</p>
4.1) Add in nav.component.ts file
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../auth.service';
#Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
constructor(public auth: AuthService) { }
ngOnInit() {
}
}
5) Create service page Add below code in authservice.ts
ng g service auth
import { Injectable } from '#angular/core';
import { Router } from '#angular/router';
#Injectable()
export class AuthService {
constructor(private myRoute: Router) { }
sendToken(token: string) {
localStorage.setItem("LoggedInUser", token)
}
getToken() {
return localStorage.getItem("LoggedInUser")
}
isLoggedIn() {
return this.getToken() !== null;
}
logout() {
localStorage.removeItem("LoggedInUser");
this.myRoute.navigate(["Login"]);
}
}
6) add content in login.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { AuthService } from '../auth.service';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
form;
constructor(private fb: FormBuilder,
private myRoute: Router,
private auth: AuthService) {
this.form = fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required]
});
}
ngOnInit() {
}
login() {
if (this.form.valid) {
this.auth.sendToken(this.form.value.email)
this.myRoute.navigate(["home"]);
}
}
}
6.1) add in login.component.html page
<form [formGroup]="form" (ngSubmit)="login()">
<div>
<input type="email" placeholder="Email" formControlName="email" />
</div>
<div>
<input type="password" placeholder="Password" formControlName="password" />
</div>
<button type="submit" color="primary">Login</button>
</form>
7) Add below code in app.component.html
<app-nav></app-nav>
<router-outlet></router-outlet>
https://angular.io/guide/router#canactivate-requiring-authentication
https://angular.io/guide/router#canactivatechild-guarding-child-routes
These are really good examples from the Angular.io tutorial "Tour of Heroes"
that explain really well authentication for root and child routes.

How can I hide my Navigation Bar if the component is called on all my routes (Angular4)

I know variations of this question have been asked millions of times before but I just cant seem to solve my problem.
So i'm making an accounting site and my problem is that I cant seem to be able to hide the top navigation bar from the login page and still keep it on all my other pages/routes:
I call the Navigation Bar component in app.component.html so it shows on all my pages:
(app.component.html)
<app-navbar>
<router-outlet>
The login page has simple authentication as i'm still making the template, eventually, the username and password will come from a back-end database.
The login page ts file looks like this:
export class LoginComponent implements OnInit {
emailFormControl = new FormControl('', [Validators.required,
Validators.pattern(EMAIL_REGEX)]);
UserName = new FormControl('', [Validators.required]);
password = new FormControl('', [Validators.required]);
constructor(private router: Router) { }
ngOnInit() {
}
loginUser(e) {
e.preventDefault();
console.log(e);
const username = e.target.elements[0].value;
const password = e.target.elements[1].value;
if (username === 'admin' && password === 'admin') {
// this.user.setUserLoggedIn();
this.router.navigate(['accounts']);
}
}
}
I also have a user service:
import { Injectable } from '#angular/core';
#Injectable()
export class UserService {
private isUserLoggedIn;
public username;
constructor() {
this.isUserLoggedIn = false;
}
setUserLoggedIn() {
this.isUserLoggedIn = true;
this.username = 'admin';
}
getUserLoggedIn() {
return this.isUserLoggedIn;
}
}
I've seen answers regarding Auth and such but i can't seem to sculpt the answers around my code.
How do i hide the Navigation bar on the login page?
I'd appreciate any and all help. Thank you
EDIT
This is the routing file as requested by Dhyey:
import {RouterModule, Routes} from '#angular/router';
import {NgModule} from '#angular/core';
import { LoginComponent } from './login/login.component';
import { AdminComponent } from './Components/admin/admin.component';
import { AccountsComponent } from './Components/accounts/accounts.component';
import { MappingComponent } from './Components/mapping/mapping.component';
const appRoutes: Routes = [
{ path: '',
pathMatch: 'full',
redirectTo: 'login' },
{
path: 'login',
component: LoginComponent
},
{
path: 'admin',
component: AdminComponent
},
{
path: 'accounts',
component: AccountsComponent
},
{
path: 'mapping',
component: MappingComponent
},
];
#NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
// export const routingComponents = [MappingComponent, AccountsComponent, AdminComponent, LoginComponent];
EDIT 2
This is the app.component.ts file
import { Component } from '#angular/core';
import {FormControl} from '#angular/forms';
import {HttpModule} from '#angular/http';
import { UserService } from './services/user.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent {
title = 'app';
myControl: FormControl = new FormControl();
}
You can check if user is logged in through your getUserLoggedIn method:
First you need to inject UserService in app.component.ts:
constructor(public userService: UserService ) { }
Then in your html:
<app-navbar *ngIf="userService.getUserLoggedIn()">
<router-outlet>
This way only when isUserLoggedIn is true, the app-navbar will be shown
What you can also do is let your menu in app component (this is not the problem), and use a route condition to display it or not.
For that, angular provides ActivatedRoute to get info from the current route url https://angular.io/api/router/ActivatedRoute
Import ActivatedRoute or Route should be fine too
Inject in component
Using constructor :
constructor (private activatedRoute: ActivatedRoute / Route) {
this.currentPage = activatedRoute.url;
}
Then check onInit the route info like below
if (this.curentPage === 'admin') { this.displayMenu = false; }
Finally, use your <div class="menu" *ngIf="! displayMenu">...</div>

Categories

Resources