如何自动检测已登录的用户并将其转至仪表板页面,而无需再在Ionic 4和firebase中登录

问题描述 投票:1回答:2

我在Ionic 4和firebase有一个项目。我不希望用户每次使用该应用程序时都会登录。它应该是自动登录。我该怎么做才能做到这一点?

这是我的登录页面代码。 login.page.html

<ion-content padding>
 <div class="ion-text-center">
   <h2>Login</h2>
 </div>
 <ion-item>
   <ion-label position="floating">Email</ion-label>
   <ion-input type="text" [(ngModel)]="email"></ion-input>
 </ion-item>

 <ion-item>
   <ion-label position="floating">Password</ion-label>
   <ion-input type="password" [(ngModel)]="password"></ion-input>
 </ion-item>

 <ion-button color="danger" expand="block" (click)="loginUser()">Login</ion-button>
 <ion-button color="primary" expand="block" (click)="gotoRegister()">Register</ion-button>
</ion-content>

login.page.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  email: string = ""
  password: string =""
  constructor(private router: Router, public afauth: AngularFireAuth) { }

  ngOnInit() {
  }

  async loginUser(){
    const {email, password} = this
    try {
      const res = this.afauth.auth.signInWithEmailAndPassword(email, password);
    } catch(err){
      console.dir(err)
      if(err.code === "auth/user-not-found"){
        console.log("User not found")
      }
    }


  }

  gotoRegister(){
    this.router.navigate(['/register']);
  }
}
javascript firebase firebase-authentication ionic4
2个回答
1
投票

您可以使用新功能离子4防护实现如下登录成功后设置状态this.storage.set('seen-intro', true);

以及代码在guards文件中的更改

async canActivate(next: ActivatedRouteSnapshot, state:RouterStateSnapshot): Promise<boolean> {
      let introSeen = await this.storage.get('seen-intro');

      if (!introSeen) {
        this.router.navigateByUrl('/intro');
      }
      return introSeen;
}

更多信息请关注此more info


0
投票

我有一个不同的解决方案。唯一的问题是返回的用户不会立即重定向到仪表板。在重定向之前最多需要10秒。我怎样才能使它更有效?

我在我的第一页中使用过它

constructor(private router: Router, public afauth: AngularFireAuth) { 
    this.afauth.authState.subscribe((user: firebase.User) => {
      if (!user) {
        this.router.navigate(['/login']);
      }else
      {
        this.router.navigate(['/home']);
      }
      return;
    });
  }
© www.soinside.com 2019 - 2024. All rights reserved.