我试图查看用户是否已登录,如果没有将其推送到登录页面

时间:2017-09-08 19:26:22

标签: angular typescript ionic-framework ionic2

我正在尝试使用ionViewWillEnter来检查用户是否已登录。如果它返回false,则将其指向登录页面。然后我想要调用intializeapp函数。我是Angular和Ionic的新手,所以任何提示都会有所帮助。 `

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();
    }
  }`

1 个答案:

答案 0 :(得分:1)

有一个名为Guard的角度有一个漂亮的概念,您可以使用它来处理角度应用程序中的整个登录流程。

您可以创建一个auth警卫并将其放在您的路由器或任何地方,并强制用户登录页面,以防他们未登录并尝试访问该网站的私人区域。

这是一个简单的授权警卫

@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;
    })

  } 
}

在您的路由器中,您可以像这样使用

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