"Angular2: The Mysterious Disappearance of the Router

I'm facing an issue with defining a redirect from my login to the dashboard after successfully verifying a user. When I try to implement "this.router.navigate(['/dashboard'])" in my login component, I encounter the following error: "exception: undefined is not an object (evaluating 'this.router')"

Below is how I structured the function:

export class ContactComponent implements OnInit {
  contactForm: FormGroup;
  errorMsg:string = '';

  constructor(private formBuilder: FormBuilder, private _router: Router) {
            this._router = _router;
          }

  ngOnInit() {
    this.contactForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
    });
    DBEventProxy.instance(); // Init Eventbus
  }

  submitForm(): void {
    DBEventProxy.instance().dbevent.login(this.contactForm['username'], this.contactForm['password'], this.loggedIn, this.failed);
  }

  loggedIn(): void {
    this._router.navigate(['/dashboard']);
    console.log("success");
    DBEventProxy.instance().dbevent.register("disconnected", function (message) {
      console.log("Client disconnected: " + JSON.stringify(message));
    });
    DBEventProxy.instance().dbevent.register("status", function (message) {
      console.log("Client reconnected: " + JSON.stringify(message));
    });
    DBEventProxy.instance().dbevent.register("routeravailable", function (message) {
      console.log("Router Available: " + JSON.stringify(message));
    });
    DBEventProxy.instance().dbevent.register("routerunavailable", function (message) {
      console.log("Router Unavailable: " + JSON.stringify(message));
    });
    DBEventProxy.instance().dbevent.listen();
    DBEventProxy.instance().dbevent.send({msgtype: "dashboardready"});

  }
failed(message: string): void {
console.log("failed: " + message);


}
}

I would greatly appreciate any assistance with this issue!

Update: I am encountering errors when attempting to log in using my credentials. The ConnectReply from the Server is received and the connection exists, but the redirect fails to work. Here are the specific errors I have identified:

  1. EXCEPTION: undefined is not an object (evaluating 'this._router')
  2. ORIGINAL STACKTRACE: (multiple documents and handleErrors included)
  3. TypeError: undefined is not an object (evaluating 'this._router')

Routes configuration:

export const rootRouterConfig: Routes = [
      { path: 'dashboard', component: DashboardComponent },
      { path: 'contact', component: ContactComponent },
      { path: '', redirectTo: '/contact', pathMatch: 'full'}
    ];

Answer №1

New response

To improve your code, consider removing this line from the constructor:

this._router = _router;

When using TypeScript and declaring constructor arguments as public or private, the class property will be automatically initialized.

Latest Update

It seems like there might be an issue with how this._router is being accessed. In the submitForm method, you could try changing

this.loggedIn

to

()=>{this.loggedIn()}

Answer №2

Give this a try!

      Navigate to the dashboard using this code:
this._router.navigate(['dashboard']);

This will take you to different routes.

  Here is the root router configuration:

export const rootRouterConfig: Routes = [

  { path: '', component: ContactComponent},
  { path: 'dashboard', component: DashboardComponent },
  { path: 'contact', component: ContactComponent },
  { path: '**', redirectTo: '' }
];

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

Guide on integrating a newly bought template into an Angular 6 and Bootstrap 4 application

Although I have years of experience as a backend developer, I am relatively new to frontend development. Lately, I have been immersing myself in learning Angular 6 and Bootstrap 4 for an upcoming project at work. After setting up a basic Angular 6 applica ...

Stop the MatSort feature from activating when the space key is pressed in Angular Material

I am currently using angular material tables and have implemented filters for each column. The filter inputs are located in the row header of each column, which is working fine. However, I am facing an issue where whenever I type and press the space key, ...

javascript identify dissimilarities within arrays

Working on an Angular 2 application and attempting to identify the difference between two arrays (last seven days and missing dates within the last seven days). Everything works fine when initializing the array through a string, like in example code 1. How ...

What's Preventing TypeScript Enum Keys from Being Transformed during Compilation?

I've encountered an issue while working on a project with TypeScript, Webpack, Babel, and React. The problem arises when trying to use enum members as keys for an object. Here's a snippet of the problematic file: // traits.ts import { Trait } fr ...

Developing JSON objects with Typescript

What is the best approach to generate and store an array of JSON objects when a new item is added? The issue I am currently facing is: Is it necessary to create a class object before saving JSON objects, or can they be saved directly? What method shoul ...

Tips for using CanActivate in Angular 5 with angular2-jwt

I am in the process of incorporating the canActivate class to manage URL access. To handle token loading, I have created the following functions: saveToken(jwt:string){ this.jwtToken = jwt; localStorage.setItem('token',jwt); let jwtH ...

Using Angular 5 to showcase multiple charts with Chart.js, each chart appearing on its own tab

I have successfully displayed a single chart, but I am facing an issue while trying to display that chart for each tab of a mat-tab-group with different data on each tab. The chart is a part of a larger dashboard consisting of multiple charts, and I have i ...

The error message "Property 'DecalGeometry' is not found in the type 'typeof "..node_modules/@types/three/index"'."

Within my Angular6 application, I am utilizing 'three.js' and 'three-decal-geometry'. Here is a snippet of the necessary imports: import * as THREE from 'three'; import * as OBJLoader from 'three-obj-loader'; import ...

Awaiting a response before triggering

Currently, I'm utilizing Serverless to build a REST get endpoint. The main goal is to request this endpoint and receive a value from the DynamoDB query (specifically from the body tag). The issue I am facing is that when this endpoint is invoked, the ...

The property is not found in the '{}' type but is necessary in the type... Typescript connect strategy

Hello, I am currently trying to establish a connection pattern for React with TypeScript. I have a reducer set up as follows: type State = { version: number, a?: string } interface ActionC { type: string payload?: number } type IAction = Action ...

Using TypeScript classes along with functions to capture JSON data

When working with reactive forms, I encountered an issue understanding how data is mapped to form controls. Let's consider an object control with id and name properties, displayed as an input textbox where the user inputs the id. Utilizing autocomplet ...

Error message: The specified type is incomplete and lacks certain properties, according to Typescript

I'm encountering an error that's hindering the deployment of my website on Vercel. Any assistance would be greatly appreciated. Usually, I retrieve the pageInfo data from Sanity and use it on my website. The issue lies in this peculiar TS error t ...

New to React and struggling with updating the DOM

Upon receiving a React project, I am faced with the task of performing a complex state update on my DOM. Here is how my component looks: /** @jsx jsx */ import { jsx } from '@emotion/core'; import { Typography } from '@material-ui/core&ap ...

The promise object is displayed instead of the actual data retrieved from the API call

I am currently working on fetching data from an API and showcasing the name of the returned data on the front end. This function successfully retrieves the data through an API call: async function retrieveData(url){ var _data; let response = await fetch( ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Passing information from the main component to a service through API connections

Currently, I am in the process of developing a website dedicated to showcasing the top 20 highest-rated Sci-fi movies. The main component on the homepage leverages a GET request via a service to fetch an array of objects containing the movie data. This mov ...

Is Angular's ngOnChanges failing to detect any changes?

Within one component, I have a dropdown list. Whenever the value of the dropdown changes, I am attempting to detect this change in value in another component. However, I am encountering an unusual issue. Sometimes, changing the dropdown value triggers the ...

Angular control reset event allows you to reset form controls to their

I'm in the process of creating my own component and I need to implement a custom reset feature. This involves cleaning up certain labels and other elements. Whenever this.form.reset(); is called, I want my component to detect this event and perform s ...

The module '@storybook/react' or its associated type declarations could not be located. This issue appears to be occurring specifically on Heroku

I encountered an issue when trying to deploy my app on Heroku, receiving the following message: https://i.sstatic.net/FeRcQ.png My application, built with TypeScript and React, is what I aim to deploy on Heroku. I am utilizing storybook/react within my p ...