Angular error: The function redirectToLogin in src_app_app_routing_module__WEBPACK_IMPORTED_MODULE_0__.AppRoutingModule is not defined

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.

image description

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']);
}

Answer №1

To properly call the function, make sure it is inside the class as a class element!

It should be formatted like this:


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 {
  constructor(private router: Router) {
    
  }

  redirectToLogin(): void {
    this.router.navigate(['login']);
  }

}

Then, include AppRoutingModule in the constructor of your component and call the method using it like:

home.component.ts

constructor(private GetRequest: LocationService,
            private appRoutingModule: AppRoutingModule) {
    try {
      this.fetchLocation();
    } catch (error) {
      console.log("Error");
    }
}

And in the function:

getBookingFormData() {
    if (this.validateForm()) {
      let currentUser = JSON.parse(localStorage.getItem('currentUser'));
      if (currentUser == null) {
        alert("Please login to book a trip");
        appRoutingModule.redirectToLogin();
      }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When deploying, an error is occurring where variables and objects are becoming undefined

I've hit a roadblock while deploying my project on Vercel due to an issue with prerendering. It seems like prerendering is causing my variables/objects to be undefined, which I will later receive from users. Attached below is the screenshot of the bui ...

Ways to parse the data from a response received from an Axios POST request

After sending the same POST request using a cURL command, the response I receive is: {"allowed":[],"error":null} However, when I incorporate the POST request in my code and print it using either console.log("response: ", resp ...

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Exploring the integration of angular with html5 history.pushstate for navigation

Currently, I am enhancing my web application by implementing a new feature. This feature involves writing a script and loading it via a tag manager. The purpose of this script is to target specific UI components, remove them from the DOM, and inject new DO ...

Tips for embedding HTML/CSS snippets in backticks when using TypeScript with AngularJS

Does anyone else experience the issue of their Angular 2 templates showing up as gray text in Visual Studio Code? I'm unable to use autocomplete or see my CSS properly. Is this a settings problem or is there a plugin that can solve this? BTW, I am us ...

Utilizing Angular's Dependency Injection to Provide Services to External Libraries

I'm currently developing an NPM package that enhances the functionalities of Material Datatable. One standout feature is the ability to specify a method that will be triggered when a user clicks on a specific cell. Here is how the property is defined ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Before users can apply any filters, all items must be loaded into an Observable<Hero[]> array

Is there a way to modify the Angular 2 Tour of Heroes search component so that it displays all items on page load (showing all Heroes) and then makes a new request to get filtered results only when a filter is provided? import { Component, OnInit } from & ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

Implement new interface methods on-the-fly

I am seeking a way to dynamically incorporate methods that are defined in an interface. Initially, I considered using the index signature approach, but unfortunately, not all methods have the same signature. My objective is to preserve all type information ...

Enhancing RxJS arrays of Observables with supplementary data for preservation

Question: Processing Array of Observables with Metadata in Angular How can I process an array of Observables, such as using forkJoin, while passing additional metadata for each Observable to be used in the pipe and map functions? const source = {animal: & ...

The search for d.ts declaration files in the project by 'typeRoots' fails

// Within tsconfig.json under "compilerOptions" "typeRoots": ["./@types", "./node_modules/@types"], // Define custom types for Express Request in {projectRoot}/@types/express/index.d.ts declare global { namespace Express { interface Request { ...

Is there a way to reveal only the version information from the package.json file in an Angular 17 project?

Is there a secure way to extract and display only the version from a package.json file on the UI of a web application without exposing the rest of its contents? I am currently using the following structure in my package.json: { "name": "exa ...

JavaScript now has Type Inference assistance

When attempting to utilize the Compiler API for processing JavaScript code and implementing Type inference to predict types of 'object' in a 'object.property' PropertyAccessExpression node, I encountered some issues. Some simple example ...

Keeping the view up to date with changes in an Array in Angular

After extensive research through various posts and Google searches, I have yet to find a solution to this particular issue. I have explored the following two links without success: Angular doesn't update view when array was changed Updating HTML vi ...

Create generic functions that prioritize overloading with the first generic type that is not included in the parameters

I encountered an issue while utilizing generic overload functions, as demonstrated below in the playground. The generic type T1 is solely used in the return type and not the parameters. Therefore, when attempting to use overload #2, I am required to speci ...

Encountering an error in Angular 8 with the plugin: Unhandled ReferenceError for SystemJS

I recently followed a tutorial on integrating plugins into my Angular application at this link. I'm trying to create a component in my Angular app that can execute and display an external component. However, I encountered the following error: Uncaugh ...

The process of building an Angular package results in the creation of if(false) {...}

I'm currently working on an Angular package repository hosted on GitHub at https://github.com/marcobuschini/parking-widget. All my tests pass successfully and there are no errors when I build using ng build. However, the resulting code contains some i ...

What is the best way to attach an attribute to a element created dynamically in Angular2+?

After reviewing resources like this and this, I've run into issues trying to set attributes on dynamically generated elements within a custom component (<c-tabs>). Relevant Elements https://i.stack.imgur.com/9HoC2.png HTML <c-tabs #mainCom ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...