I'm attempting to redirect users from the homepage to the login page using home.component.ts. Within this file, I've invoked a static method called "AppRoutingModule.redirectToLogin()" that I've defined in app-routing.module.ts by importing Router.
Please review my code
home.component.ts
Check the method call AppRoutingModule.redirectToLogin()
import { Component, OnInit } from '@angular/core';
import { LocationService } from 'src/app/service/location.service';
import { AppRoutingModule } from 'src/app/app-routing.module';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
//Variables for HTML file
stringifiedData: string[] = [];
Location: any;
booking = {
from !: "",
to !: "",
date !: ""
}
fetchLocation()
{
this.GetRequest.fetchLocation().subscribe(data => {
this.Location = data;
for (let i = 0; i < Object.keys(this.Location).length; i++)
{
this.stringifiedData.push(this.Location[i].locationName);
}
});
}
getBookingFormData()
{
if (this.validateForm())
{
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser == null)
{
alert("Please login to book a trip");
AppRoutingModule.redirectToLogin();
}
}
}
validateForm()
{
if (this.booking.from == "" || this.booking.to == "" || this.booking.date == "")
{
alert("Please fill in all the fields");
return false;
}
else if (this.booking.from == this.booking.to)
{
alert("Please select different destinations");
return false;
}
else if (this.booking.date < new Date().toISOString().split('T')[0])
{
alert("Please select a future date");
return false;
}
else
{
console.log(this.booking);
return true;
}
}
constructor(private GetRequest : LocationService) {
try {
this.fetchLocation();
} catch (error) {
console.log("Error");
}
}
ngOnInit(): void {
}
}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Router, RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './Componentes/home/home.component';
import { LoginComponent } from './Components/login/login.component';
import { SignupComponent } from './Components/signup/signup.component';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'login/signup', component: SignupComponent },
{ path: '', component: HomeComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
static redirectToLogin: any;
constructor(private router: Router)
{
}
}
function redirectToLogin() : void
{
this.router.navigate(['login']);
}