简体   繁体   中英

Angular2 .subscribe sometimes does not fire the router.navigate

I've a login function:

login(user: UserComponent) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append("Authorization", "Basic " + btoa(user.username + ":" + user.password)); 
return this._http
  .get(
    'https://api.xxxxxxxxxxxx.com/rest/auth', 
    { headers }
  )
  .map(res => res.json())
  .subscribe(
    (data) => {
      this.loggedIn = true;
      console.log('data '+ this.loggedIn);
      localStorage.removeItem('auth_token');
      localStorage.setItem('auth_token', data.token);
      console.log(data.token);
      this._router.navigate(['']); 
    },
    (err) => {
      this.errorMsg = err.json().error_message
      console.log(this.errorMsg);
    }
  );}

isLoggedIn() {
    if(this.loggedIn){
      return true;
    }else{    
      this._router.navigate(['login']);
      return false;
    }
  }

that I call like this:

   constructor(private _userService: UserService, private _router: Router) {}

authUser() {
  let user = new UserComponent(this.username, this.password);
  this._userService.login(user);

}

the CanActivate goes like this:

@Injectable()
export class LoggedInGuard implements CanActivate {
  constructor(private _userService: UserService) {}

  canActivate() {
    console.log(this._userService.isLoggedIn());
    return this._userService.isLoggedIn();
  }

}

UPDATE #1 I think I found the problem, but don't know how to solve. I updated the code above with the current version.

Looks like the problem is when it performs the action the Guard runs before the this.loggedIn is set to true.... returning false yet... why? how do I fix this?

Thank you

You login function is asynchronous and that is why console.log happening before you get data from your service. You need to wrap console.log in you login function to see data

this._userService.login(user).subscribe(
  (data) =>{
    this.data = data
    console.log(this.data);
   },
(err) => this.errorMsg = err.json().error_message);

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