使用@ionic/storage提供的Ionic Storage模块来保存认证数据,以便在启动应用程序时进行自动登录。
import { Storage } from '@ionic/storage';
// Save auth data to storage async saveAuthData(authData: any) { await this.storage.set('authData', authData); }
在AppComponent中的ngOnInit方法中使用Ionic Storage模块获取本地存储的认证数据,以便在应用程序启动时自动登录。
import { Component, OnInit } from '@angular/core'; import { Storage } from '@ionic/storage'; import { AuthService } from './auth.service';
@Component({ selector: 'app-root', templateUrl: 'app.component.html' }) export class AppComponent implements OnInit { constructor(private storage: Storage, private authService: AuthService) {}
async ngOnInit() { const authData = await this.storage.get('authData'); if (authData) { this.authService.loginWithAuthData(authData); } } }
AuthService负责登录用户并将认证数据存储到本地存储中。当自动登录时,它会接收保存的authData并使用它来进行登录。
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' }) export class AuthService { constructor(private storage: Storage, private http: HttpClient) { }
async login(email: string, password: string) { const response = await this.http.post('/login', { email, password }).toPromise(); this.saveAuthData(response); }
async loginWithAuthData(authData: any) { const response = await this.http.post('/loginWithToken', authData).toPromise(); this.saveAuthData(response); }
async saveAuthData(authData: any) { await this.storage.set('authData', authData); } }