0

I am using the JS Library with Parse Server and having issues navigating to another page on successful login.

Using this function this.navCtrl.setRoot(TemplatesPage); doesn't do anything in my app.

My full code is below and I can confirm in the console that the success function is being called and I have also tried pop before I tried 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);
  }

}

Console showing success and no error

Taylorsuk
  • 1,339
  • 13
  • 43

2 Answers2

2

The this used inside the function(user) will not refer loginPage. It refers to your function. Arrow functions behave differently, they fix the problem with this. The answer here expalins when to use arrow functions. Try then and catch 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();

    });
  }
Community
  • 1
  • 1
Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
1

Someone may know why, however thanks to the commenters I replaced .then with => and it works.

Completed 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();
})
Taylorsuk
  • 1,339
  • 13
  • 43
  • The reason is because of the context. When using `user => { //... }` you still can access to the component properties and thus, to `this.navCtrl...` but if you don't, the component properties are not available there because `this` points to something different than the component. – sebaferreras Dec 28 '16 at 09:54