简体   繁体   中英

router.navigate() doesn't redirect inside .subscribe

I have a login function like so:

login() {

  // clear error text
  this.state.errorText = "";

  // try to login
  this.sb.login(this.model.username, this.model.password).subscribe(x => {
    // check if ok
    if (x.success) {
      console.log('does this print') //<-- outputs as expected
      this.router.navigate(['/app']); 
    } else {
      this.state.errorText = x.response;
    }        
  });
}

Through debugger I can see the x.success comes back as true. My console.log prints but after, the this.router.navigate(...) line doesn't seem to do anything. there is no redirect.

I've tried to use:

this.zone.run(() => this.router.navigate(['/app']));

but that results in the same, no page redirect.

1 Assign Route Service Locally 2 Use the Assigned Local Service

login() {
  this.state.errorText = "";
  var route = this.router; // Assign router locally 

  // try to login
  this.sb.login(this.model.username, this.model.password).subscribe(x => {
    // check if ok
    if (x.success) {
      console.log('does this print') //<-- outputs as expected
      route.navigate(['/app']); // use local route service
    } else {
      this.state.errorText = x.response;
    }        
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM