简体   繁体   中英

I am trying to see if the user is logged in and if not push them to the login page

I am trying to use ionViewWillEnter to check to see if the user is logged in. If it returns false then direct them to the login page. Then I want the intializeapp function to be called. I am fairly new to Angular and Ionic so any tips will help. `

ionViewCanEnter() {
    console.log("1");
    console.log(this.userSevice.isUserLoggedIn());
    if (this.userSevice.isUserLoggedIn() === false){
      this.nav.push(LoginPage);
      alert("user is logging in");
    }
    else{
      this.initializeApp();
    }
  }`

There is a beautiful concept in angular called Guard and you can use that to handle your entire login flow in angular application.

You can create an auth guard and place it in your router or anywhere and force the user to the login page in case they are not logged in and trying to access a private area of the site.

this is a simple auth guard

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) { }

  canActivate(): Observable<boolean> | boolean {
    // here check if this is first time call. If not return 
    // simple boolean based on user object from authService
    // otherwise:

    return this.authService.getAuthenticated.map(user => {
          this.authService.setUser(user);
          return user ? true : false;
    })

  } 
}

and in your router, you can use like this

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuardService],
    runGuardsAndResolvers: 'always',
  }
   ...
]

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