Using NavController.setRoot within a resolved Promise in an Ionic 2 application

I am currently facing an issue with navigating to another page after a successful login while using the JS Library with Parse Server.

When I try to use

this.navCtrl.setRoot(TemplatesPage);
, it doesn't seem to have any effect in my application.

After confirming that the success function is triggered based on the console logs, I also attempted using pop before resorting to setRoot.

import { Component } from '@angular/core';
import { NavController, AlertController} from 'ionic-angular';
import { User } from '../../models/user-model';
import { SignupPage } from '../signup/signup';
import { TemplatesPage } from '../templates/templates';
import Parse from 'parse';

@Component({
  selector: 'login',
  templateUrl: 'login.html'
})
export class LoginPage {

  user : User = {
    username : '',
    password: ''
  }

  constructor(public navCtrl: NavController, public alertCtrl: AlertController) {

  }

  login() {

    Parse.User.logIn(this.user.username, this.user.password).then(function(user) {

      console.log('Success' + user);

      this.navCtrl.setRoot(TemplatesPage);

    }, function(err) {

      this.alertCtrl
       .create({title: "Error", message: err.text(), buttons: [{
         text: 'OK',
       }]})
       .present();

    })
  }

  goToTemplatePage() {
    this.navCtrl.push(TemplatesPage);
  }

  gotToSignup() {
    this.navCtrl.push(SignupPage);
  }

}

https://i.stack.imgur.com/Wyz14.jpg

Answer №1

When using the function(user), the context of "this" will not be referencing loginPage, but rather your current function. Arrow functions offer a solution to this issue by behaving differently with regards to "this". For more information on when to use arrow functions, check out the answer provided here. Try utilizing try and catch blocks with arrow functions:

 Parse.User.logIn(this.user.username, this.user.password).then((user) => {

      console.log('Success' + user);

      this.navCtrl.setRoot(TemplatesPage);

    }).catch((err) => {

      this.alertCtrl
       .create({title: "Error", message: err.text(), buttons: [{
         text: 'OK',
       }])
       .present();

    });
  }

Answer №2

It is unclear why, but thanks to the comments from others, I made a change from .then to => and it now functions properly.

See revised function below:

Parse.User.logIn(this.user.username, this.user.password).then(user => {
  console.log('Success' + user);
  this.navCtrl.setRoot(TemplatesPage);

}, err => {
  console.log('error called')
  this.alertCtrl
   .create({title: "Error", message: err.text(), buttons: [{
     text: 'OK',
   }]})
   .present();
})

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

Encountered an issue with ionViewDidLoad: The property 'firstChild' cannot be read as it is null

While working on an Ionic 2 App with Angular2 and Typescript, I encountered an issue when trying to pass a JSON to map for markers. Here is the link to the gist containing the code snippet I am facing an error that reads: view-controller.js:231 MapPage i ...

Angular CLI's selection of third-party libraries that are not available on npm repositories

Currently in the process of migrating an app from Angular 2 to Angular CLI Now facing the challenge of importing 3rd party libraries like orbitcontrols.js that are not available on npm or bower. After researching on https://github.com/angular/angular-cli ...

Choosing the Active Browser Tab while Modal is Open in Angular

In my current situation, I have implemented a function in the first tab that displays a modal or component after 5 seconds: ngOnInit() { setTimeout(() => { this.openDialog(); }, 5000); } openDialog() { this.dialog.open(.....); } However, if ...

Angular is throwing an error with code TS2322 stating that a number cannot be assigned to a string type

While trying to convert a PHP variable gender from string to number, I ran into the following error: Error TS2322: Type 'number' is not assignable to type 'string' in Angular Here's the code snippet: param = { id: '&ap ...

Exit the current dialog and switch to a different route while encountering difficulties with an open dialog in Angular 4

I've spent several hours searching, but couldn't find a similar post. Here's the issue I'm facing: When I click a button in the routeA component, it navigates to routeB and opens dialogB. After closing dialogB, it should navigate back ...

Encountering a problem with indexing when attempting to include dynamic input text within a form in Angular 6

Whenever I click the "Add" button, a dynamic input text box is added to the form. However, if I remove any input box (except for the last one), the second-to-last input box becomes empty. I'm not sure what the issue might be. Here is the HTML section ...

Choose FormGroup using Angular Directive

Can Angular reactive form controls be selected for a custom directive in a different way? Take a look at this code snippet: @Directive({ selector: '[formControl], [formControlName]', }) export class MyDirective { constructor( priv ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

The modal feature on ng-bootstrap.github.io is failing to function properly when used with the Bootstrap3 CSS

Struggling to understand why the modal displays when using Bootstrap 4 with ng-bootstrap, but not displaying with Bootstrap 3. ...

A guide on organizing similar elements within an array using Angular

Could you assist me in grouping duplicate elements into separate arrays of objects? For example: array = [{key: 1}, {key: 5}, {key: 1}, {key: 3}, {key: 5}, {key: 1}, {key: 3}, {key: 2}, {key: 1}, {key: 4}]; Expected output: newArrayObj = {[{key: 1}, {key ...

The visual representation remains unchanged even after updating the model

I'm currently tackling an issue with my football project, specifically when updating a service model. The project involves two key components - AvailablePlayers and SelectedPlayers, as well as two corresponding services - AvailablePlayersService and S ...

Tips for successfully utilizing hyphens when passing an object property as an argument

Does anyone know how to pass an object property with a hyphen in it as an argument? I'm having trouble with this issue. Object { "section-id": 1, ... } HTML <div *ngFor="let section of sections" (trackScrollLeave)="leave(section.sectio ...

What steps should be followed to implement ng-zorro-antd?

I'm currently in the process of developing an Angular project with ng-zorro. I've followed these steps: npm install --location=global @angular/cli ng new ng-zorro-demo This Angular project includes routing. cd ng-zorro-demo/ ng add ng-zorro-antd ...

Encountering challenges when trying to incorporate error-handling functionality into Highcharts

I've been attempting to incorporate custom error handling in Highcharts by utilizing the Highcharts.error function within my Angular 7 application, but it's resulting in an error. Highcharts.error = function (code: string): void { }; Error T ...

What is the process of combining two states in Angular?

Having a state defined as: export interface ChatMessagesState { messages: Message[] | null; chatId: string; } and receiving data in the websocket like: newMessages: Message[] = [ { text: 'Hello', chatId: '100' }, { text ...

Exploring the functionalities of class methods within an Angular export function

Is it possible to utilize a method from an exported function defined in a class file? export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: AzureService.getConfiguration(), <-------- Com ...

Unable to retrieve rxjs resource

After upgrading to rxjs 5.4.3, I encountered an error in the browser. Despite having "rxjs": "5.4.3" installed in my package.json, I cannot seem to resolve this error message. Here's the content of my ts file: import { Injectable ...

What is the process for extracting the background color from a typescript file in Angular and connecting it to my HTML document?

My typescript array population is not changing the background color of my div based on the values in the array. I've attempted to set the background using [style.backgroundColor]="statusColor[i]", where statusColor is an array declared in my typescrip ...

On which platform is the getFeatureInfo request constructed using Cesium?

Currently, I am working with Cesium and Angular. I am trying to locate where the request URL is generated for GetFeatureInfo in Cesium, but unfortunately I am unable to find it. My goal is to display feature information when clicking on the map. However, ...

Updating the log file location for electron-log in an Angular application integrated with Electron

I am currently developing a project using Angular 6 integrated with Electron. I have managed to successfully incorporate the electron-log library using ngx-electron. As a result, my application is functioning well and logging data to the default path: C:&b ...