0

I am using Parse (an external JS lib) inside Angular JS 2. However, when I try calling the function gotoMain() from inside a call back function of Parse, it looks like things are not loaded properly. For example, when routing to 'Main' as in the code below, Main is loaded, however, the variables in Main are not bound properly and ngOnInit in Main is not called.

export class LoginComponent {
  username: string;
  password: string;
  msg: string;

  constructor(private _router: Router) {
    console.log("in Login component constructor");
  }

  onSubmit() {
      Parse.User.logIn(this.username, this.password, {
        success: function(user) {
          this.gotoMain();
        }.bind(this),
        error: function(user, error) {
          // The login failed. Check error to see why.
          this.msg = error.message;
        }.bind(this)
      });
  }

  gotoMain() {
    console.log("gotoMain with user: " + this.username); // works fine
    this._router.navigate(['Main']);
  }

}
egsemsem
  • 111
  • 3

2 Answers2

0

Run the code in Angulars zone explicitely:

export class LoginComponent {
  username: string;
  password: string;
  msg: string;

  constructor(private _router: Router, private zone:NgZone) {
    console.log("in Login component constructor");
  }

  onSubmit() {
      Parse.User.logIn(this.username, this.password, {
        success: (user) => {
          this.zone.run(() => this.gotoMain());
        },
        error: (user, error) => {
          // The login failed. Check error to see why.
          this.zone.run(() => this.msg = error.message);
        }
      });
  }

  gotoMain() {
    console.log("gotoMain with user: " + this.username); // works fine
    this._router.navigate(['Main']);
  }
}

Code running outside Angulars zone breaks Angulars change detection. Using zone.run() brings the execution back into Angulars zone.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

I found the solution, call the function in NGZone:

this._ngZone.run(() => {this.gotoMain() });

Moe info can be found here: View is not updated on change in Angular2 and here: https://angular.io/docs/ts/latest/api/core/NgZone-class.html

Community
  • 1
  • 1
egsemsem
  • 111
  • 3