Cannot read property 'navigate' of undefined in Angular
Asked Answered
C

3

5

All help articles on this error for Angular say to make sure one has injected 'Router' like this:

constructor(router: Router....

Which I have done.

I'm unsure what else to do. I have to fix this before I start troubleshooting the routes.

My Goals: Allow the user to navigate to a child route. Allow the user to close the current route on click.

So the current address would be: https://localhost:4200/layout/usermanagement/(newuser:newuser/(newuserinput:newuserinput))

After clicking I would be routed to: https://localhost:4200/layout/usermanagement/(newuser:newuser/(newuserorginfo:newuserorginfo))

Also, after clicking another button I would be routed to: https://localhost:4200/layout/usermanagement/(newuser:newuser))

Here is my Component, Module, and Template.

COMPONENT new-user-input.component.ts

import { Component, OnInit } from '@angular/core';
import { slideToRight } from '../../../../router.animations';
import { Router, ActivatedRoute, UrlSegment } from '@angular/router';

@Component({
  selector: 'app-new-user-input',
  templateUrl: './new-user-input.component.html',
  styleUrls: ['./new-user-input.component.css'],
  animations: [slideToRight()]
})
export class NewUserInputComponent implements OnInit {
  router: Router;

  constructor(router: Router, r: ActivatedRoute) {
    r.url.subscribe((s: UrlSegment[]) => {
      console.log("url", s); //https://vsavkin.com/angular-router-understanding-router-state-7b5b95a12eab
    });
  }

  ngOnInit() {
  }

  displaySibling() {
    console.log(this.router);
    this.router.navigate(['../', { outlets: { newuserorginfo: ['newuserorginfo'] } }])
  }

  closeBlade() {
    this.router.navigate([{ outlets: { newuserinput: null } }]);
  }

}

MODULE user-management.module.ts

import { HttpModule, JsonpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
// import 'rxjs/add/operator/map';
import { NgModule, Type, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';

import { GridAllModule } from '@syncfusion/ej2-ng-grids';
import { HttpClientModule } from '@angular/common/http';
import {
  GridModule, ToolbarService, EditService, SortService, GroupService, FilterService, PageService,
  ContextMenuItem, PdfExportService, ExcelExportService, ContextMenuService, ResizeService,
  DataSourceChangedEventArgs, DataStateChangeEventArgs
} from '@syncfusion/ej2-ng-grids';


import { UserManagementComponent } from './user-management.component';
import { PageHeaderModule } from './../../shared/page-header/page-header.module';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';


// import { NewUserComponent } from './new-user/new-user.component';
// import { PendingUserComponent } from './pending-user/pending-user.component';
// import { ProcessUserComponent } from './process-user/process-user.component';
// import { NewUserInputComponent } from './new-user/new-user-input/new-user-input.component';

import { RouterModule } from '@angular/router';
import { NewUserOrgInfoComponent } from './new-user/new-user-org-info/new-user-org-info.component';
import { NewUserSupervisorInfoComponent } from './new-user/new-user-supervisor-info/new-user-supervisor-info.component';
import { NewUserSecurityInfoComponent } from './new-user/new-user-security-info/new-user-security-info.component'; //??????????

@NgModule({
  imports: [
    CommonModule,
    PageHeaderModule,
    GridModule,
    RouterModule,
    NgbModule
  ],
  declarations: [UserManagementComponent, NewUserOrgInfoComponent, NewUserSupervisorInfoComponent, NewUserSecurityInfoComponent],
  providers: [EditService, ToolbarService, SortService, GroupService, FilterService, PageService,
    ContextMenuService, PageService, ResizeService, PdfExportService, ExcelExportService]
})
export class UserManagementModule {
}

TEMPLATE new-user-input.component.html

<div class="blade" [@routerTransition]>
  <div class="blade-header">
    <h3>User Information</h3>
    <div class="window-functions">
      <i class="fa fa-window-minimize"></i>
      <i class="fa fa-window-restore"></i>
      <i class="fa fa-window-maximize"></i>
      <!-- <a routerLink='/layout/usermanagement/(newuser:newuser)' routerLinkActive='router-link-active'> -->
      <i (click)='closeBlade()' class="fa fa-window-close"></i>
      <!-- </a> -->
    </div>
  </div>
  <form action="submit">
    <!-- <label for="firstname">First Name:</label> -->
    First name:
    <br>
    <input type="text" name="firstname" value="Richard">
    <br> Last name:
    <br>
    <input type="text" name="lastname" value="Dawkins">
    <br> Cell phone:
    <br>
    <input type="tel" name="cellphone" value="(585) 271-8888">
    <br> Office phone:
    <br>
    <input type="tel" name="officephone" value="(585) 271-8887">
    <br> Fax:
    <br>
    <input type="tel" name="fax" value="(585) 271-8886">
    <br> City:
    <br>
    <input type="text" name="city" value="City">
    <br> State:
    <br>
    <input type="text" name="state" value="New York">
    <br> Requester title:
    <br>
    <br>
    <!-- <input type="submit" value="Next" disabled="true"> -->
    <input class="next-button" type="submit" value="Next" (click)="displaySibling()">
    <!-- <input type="submit" value="Next" [routerLink]="[{ outlets: { newuserorginfo: ['newuserorginfo '] } } ]" routerLinkActive='active '> -->
  </form>
</div>
<router-outlet></router-outlet>
<router-outlet name="newuserorginfo"></router-outlet>
Centralize answered 23/5, 2018 at 12:58 Comment(3)
Replace constructor(router: Router, ...) with constructor(private router: Router, ...), to make router a member of the component class.Doer
Can't believe that was all it was... forgot how important specifying private was since it does so much behind the scenes for you. Thanks. I will mark it as an answer as soon as you put it up as one.Centralize
You are welcome. I posted the answer. :-)Doer
D
4

The error occurs because router is not a member of the component class. Specifying the access level (private, protected or public) when injecting the service in the constructor will make router a property of the class and fix the problem:

constructor(private router: Router, ...)
Doer answered 23/5, 2018 at 18:20 Comment(0)
P
3

the issue i encountered is in the handle error of the logout method. let me show you:

public logout(): Observable<any> {
    return this.http
      .get('logout_url')
      .pipe(
        map(a => this.mapLogoutResult(a)),
        catchError(this.handleError)
      );
  }

and the handleError:

public handleError(err) {
    localStorage.setItem('isAuthenticated', 'false');
    if (this.heartbeatOn) {
      this.heartBeat.next(false);
    }
    this.router.navigate(['/login']);
    throwError(err);
    return of({ failure: err });
  }

and here i was constantly receiving:

Cannot read property 'navigate' of undefined

and i resolved it by changeing how the handleError is called in catchError

    catchError(err => this.handleError(err))

Arrow function in catchError defines the scope, so it looks like the without arrow function, function didn't had proper inputs.

Pretentious answered 29/6, 2021 at 6:32 Comment(0)
V
0

route is not injecting in the constructor
try this :

constructor(private route:Router){}
Vento answered 8/10, 2022 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.