Angular2 - receiving an error message stating that this.router.navigate does not exist as a

Currently, I am delving into the world of Angular2 with Ionic and working on crafting a login page. However, upon loading the page, an error surfaces: 'router.initialNavigation is not a function'

To address this issue, I inserted '{initialNavigation : false}' in app.routing.ts, as shown below:

@NgModule({
  imports: [ RouterModule.forRoot(appRoutes, {initialNavigation : false})],
  exports: [ RouterModule ]
})

Even after implementing the above change, another error pops up: 'router.setUpLocationChangeListener is not a function'

In addition, despite adding 'initialNavigation:false', clicking the login button triggers the following message: 'this.router.navigate is not a function'

I am stumped on identifying the root cause... Any guidance would be greatly appreciated! Below you will find my code for reference.

app.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Router, Routes, RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AppRoutingModule } from './app.routing';

import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    LoginPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    TabsPage,
    LoginPage
  ],
  providers: [//Global Services
    StatusBar,
    SplashScreen,
    {provide: Router, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

app.routing.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { TabsPage } from '../pages/tabs/tabs';
import { LoginPage } from '../pages/login/login';

const appRoutes: Routes = [
    { path: '', component: TabsPage},
    { path: '/login', component: LoginPage },
    { path: '/tabs', component: TabsPage },

    { path: '**', redirectTo: 'tabs' }
];

@NgModule({
  imports: [ RouterModule.forRoot(appRoutes, {initialNavigation : false})],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

login.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';//for .map()
import 'rxjs/add/operator/map';//for .map()
import { Router, Routes, RouterModule } from '@angular/router';

import { TabsPage } from '../tabs/tabs';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  id:string="";
  pw:string="";
  rootPage:any = TabsPage;

  constructor(public navCtrl: NavController, private http: Http, private router: Router) {

  }

  ngOnInit(){

  }

  loginAction(){
      let id:string = this.id;
      let pw:string = this.pw;

      this.http.post("http://localhost:80/loginAction", {
          id:id,
          pw:pw
      }, '').map(response => response.json()).subscribe(data => {
                this.router.navigate(['/tabs']);
                console.log(data);
      });
  }

}

login.html

<ion-header>
  <ion-navbar>
    <base href="/" />
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

    <ion-list>
      <ion-item>
        <ion-label floating>Id</ion-label>
        <ion-input type="text" value="" [(ngModel)]="id"></ion-input>
      </ion-item>

      <ion-item>
        <ion-label floating>Password</ion-label>
        <ion-input type="password" value="" [(ngModel)]="pw"></ion-input>
      </ion-item>
    </ion-list>

    <div padding>
      <button ion-button color="primary" (click)="loginAction()" block>Sign In</button>
    </div>

</ion-content>>

Answer №1

Although I don't have extensive knowledge of Ionic, it appears that you are linking Router to IonicErrorHandler in the app.module

{provide: Router, useClass: IonicErrorHandler}
is replacing the Router

UPDATE: After further investigation into the functionality of IonicErrorHandler, it seems more appropriate to use

{ provide: ErrorHandler, useClass: IonicErrorHandler }
instead of overriding the Router provider with the previous line

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

Using jQuery, Ajax, and HTML together can create dynamic

Is there a way to run JavaScript functions in an HTML file that is loaded using AJAX? The HTML file contains both text and JavaScript, but only the inline JavaScript seems to work (like onclick="dosomething();return false"). The pre-defined functions wra ...

Discovering a method to recover information obtained through intercepting an observable

I am currently working on an Angular 6 cli application where a component utilizes a service to fetch data. As part of my project, I am incorporating an ngrx store into the application. I am considering abstracting the interactions with the store within the ...

Verify whether the user is obstructing third-party domain

I've encountered a recurring issue where many of our support calls pertain to images not loading due to users blocking Amazon S3 or a similar third-party service. I rely on third-party services for hosting images, videos, and certain JavaScript elemen ...

Only the initial upload file is being passed through the Apollo Express server, with the remaining files missing in action

Currently, I am utilizing the apollo-express server with GraphQL. One issue I am encountering involves a mutation where I pass files from the front-end to the back-end. Strangely, I receive the file:{} object only for the first file - for the others, I rec ...

The object is given a value in the form of a string, even though it is a strongly-typed variable

I'm encountering something unusual in my code. In the following example, there is a (change) event that captures the current value selected by the user from a dropdown menu. <div style="padding-right: 0; width: 100%;"> <label st ...

Collection of items consists of identical objects repeated multiple times

Multiple objects are being created and then pushed into the array objArr: var objArr = []; var obj = {}; var height = [9,8,7,3,6,5,2,4]; for (var i = 0; i < 8; i++) { debugger; var mountainH = height[i]; obj.h = mountainH; obj.index = i; o ...

How can different styles be seamlessly combined when customizing Fabric components?

Imagine I am enhancing a Fabric component by adding custom styles and wishing to combine any additional styles passed in through its props. Here's the solution I've devised: const { TextField, Fabric , IButtonProps, mergeStyleSets } = window.Fab ...

Certain textboxes within a Reactive Form in Angular 6 are experiencing issues with clearing properly

I am utilizing Angular 6 along with Reactive Forms to establish a timetable containing 2 sections. The location section includes origin and destination textboxes, while the trip section, nested within the schedule, also consists of origin and destination t ...

Exploring Local Gems with Google Places API in Ionic 2

I recently integrated the Google Maps API into my app and now I am looking to incorporate Google Places as well. I have managed to successfully implement Geolocation, but I am facing difficulties when trying to perform a nearby search for "supermarkets" in ...

Is it possible to transfer elements from one array to another when clicked, but without copying the contents to the new array objects?

Welcome, For my latest project, I am excited to create a "Learning Cards" App from scratch. The concept is pretty straightforward: it consists of cards with questions. Upon clicking a button, you can reveal the correct answer. Additionally, there's a ...

Angular-oauth2-oidc does not successfully retrieve the access token when using OAuth2 and SSO

Here's an issue I'm facing: I've been attempting to integrate SSO and OAuth2 flow using angular-oauth2-oidc. When testing with POSTMAN and ThunderClient in VS Code, I managed to receive the correct response (the access_token). However, I am ...

Utilize the nests cli swagger plugin to enable compatibility with external models

Exploring the functionality of the swagger plugin provided by nestjs, I am eager to try it out. While it works smoothly when defining a class like CreateUserDto, my goal is to incorporate types from a third-party library - specifically @adyen/api-library. ...

Using vanilla JavaScript in a node.js environment alongside Functional Reactive Programming (FRP) with bacon.js

I am interested in incorporating Functional Reactive Programming (FRP) into my project. I have come across a popular library for node.js called bacon.js that implements FRP. However, I am having trouble finding examples of how to use bacon.js in native J ...

Which tools should I combine with Angular for developing both Android and iOS applications?

My primary focus has been on developing web apps using Angular, but now I am interested in creating native Android and iOS apps with Angular. I have heard about using Cordova, Capacitor, and NativeScript for this purpose, as alternatives to Ionic due to pe ...

The argument 'TabsCtrl1' is throwing an error as it is not recognized as a valid function and is showing as

I have encountered a problem with my controller, and I am seeing the following error message: Error: [ng:areq] Argument 'TabsCtrl1' is not a function, got undefined http://errors.angularjs.org/1.3.0-beta.11/ng/areq?p0=TabsCtrl1&p1=not%20a%20 ...

Enhancing the visual appeal of a standard jQuery slider with thumbnails

Recently, I incorporated the Basic jQuery slider into my website, which can be found at . As a novice in jQuery but well-versed in HTML and CSS, I have managed to make it work seamlessly on my site. However, I am curious to know if there is a way to displa ...

What steps should I take to address the issue of fixing the classname rather than using the

<div ng-class:"{{myclass}}" role="progressbar" aria-valuenow="{{roundedtotalPerformanceCount}}" aria-valuemin="0" aria-valuemax="100" ng-style="{'width' : ( totalPerformanceCount + '%' ) }"> {{roundedtotalPerformanceCou ...

Issue encountered with Azure DevOps during TypeScript (TS) build due to a type mismatch error: 'false' being unable to be assigned to type 'Date'. Conversely, the build functions correctly when run locally, despite the type being defined as 'Date | boolean'

I am facing an issue with my NestJS API while trying to build it using Azure DevOps pipeline. The build fails with the following error: src/auth/auth.controller.ts(49,7): error TS2322: Type 'false' is not assignable to type 'Date'. src/ ...

Vue.js - Axios Get request received an object response

My current project is built on Vue.js and I am using Flask for the API. The issue arises when trying to make an axios.get request - the API returns an object 'Object'. Interestingly, when testing the same request in Postman, it works fine and ret ...

Retail Shop versus Requesting Services While Out and About

Currently, I am in the process of implementing an API for Q&A on my portal and I am faced with two options: To hard code the categories into the HTML, and only load the questions from the API when the category component is opened (which will be displayed ...