从Angular JS 2中的Javascript lib进行路由

时间:2016-04-26 19:00:58

标签: javascript parse-platform angular

我在Angular JS 2中使用Parse(一个外部JS库)。然而,当我尝试从Parse的回调函数中调用函数gotoMain()时,看起来事情没有正确加载。例如,当路由到' Main'如下面的代码所示,Main已加载,但Main中的变量未正确绑定,并且未调用Main中的ngOnInit。

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']);
  }

}

2 个答案:

答案 0 :(得分:0)

明确地在Angulars区域中运行代码:

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']);
  }
}

在Angulars区域中断之外运行的代码Angulars更改检测。使用zone.run()将执行带回Angulars区域。

答案 1 :(得分:0)

我找到了解决方案,在NGZone中调用函数:

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

可以在此处找到Moe信息:View is not updated on change in Angular2和此处:https://angular.io/docs/ts/latest/api/core/NgZone-class.html