Angularjs 如何解决localStorage.getItem()错误?
我试图在用户登录数据库(firestore)时使用表单获取其数据。我使用JSON.parse(localStorage.getItem())方法在用户登录时获取数据,或者在用户注销时返回null。所以我在代码中写了这个:Angularjs 如何解决localStorage.getItem()错误?,angularjs,typescript,Angularjs,Typescript,我试图在用户登录数据库(firestore)时使用表单获取其数据。我使用JSON.parse(localStorage.getItem())方法在用户登录时获取数据,或者在用户注销时返回null。所以我在代码中写了这个: localStorage.setItem('user', JSON.stringify(this.userData)); JSON.parse(localStorage.getItem('user')); } else { local
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
但我一直收到这样一个错误:“method…localStorage.getItem()的参数类型为'string | null'…”
我有什么遗漏吗
以下是我的完整代码:
import { Injectable, NgZone } from '@angular/core';
import { Webuser } from './webuser';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from '@angular/router';
//import * as firebase from 'firebase/app';
//import 'firebase/auth';
@Injectable({
providedIn: 'root'
})
export class AuthService {
userData: any; // This saves logged in user data
constructor(
public afs: AngularFirestore, // Inject Firestore service
public afAuth: AngularFireAuth, // Inject Firebase auth service
public router: Router,
public ngZone: NgZone // NgZone service is called to remove outside scope warnings
) {
/* Saving user data in local storage when
logged in and setting up null when logged out */
this.afAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
})
}
// Login with email/password
Login(email: string, password: string) {
return this.afAuth.signInWithEmailAndPassword(email, password)
.then((result) => {
this.ngZone.run(() => {
this.router.navigate(['']);
});
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error.message);
})
}
// Signup with email/password
SignUp(email: string, password: string) {
return this.afAuth.createUserWithEmailAndPassword(email, password)
.then((result) => {
// Here we call the SendVerificationMail() method when a user signs up and returns promise
this.SendVerificationMail();
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error.message);
})
}
// Send email verification when user signs up
SendVerificationMail() {
return this.afAuth.currentUser.then(u => u.sendEmailVerification())
.then(() => {
this.router.navigate(['verify-email-address']);
})
}
// Reset Forgotten password
ForgotPasword(passwordResetEmail: string) {
return this.afAuth.sendPasswordResetEmail(passwordResetEmail)
.then(() => {
window.alert('Password reset email sent to the email you provided. Please check your inbox');
}).catch((error) => {
window.alert(error);
})
}
// This returns true when user email is verified and user is logged in
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user !== null && user.emailVerified !== false)
}
/* Setting up user data when login with username/password,
sign up with username/password in Firestore database using
AngularFirestore + AngularFirestoreDocument service */
SetUserData(user: any) {
const userRef: AngularFirestoreDocument<any> = this.afs.doc('users/${user.uid}');
const userData: Webuser ={
uId: user.uid,
name: user.name,
emailVerified: user.emailVerified
}
return userRef.set(userData, {
merge: true
})
}
// Signing out a user
SignOut() {
return this.afAuth.signOut().then(() => {
localStorage.removeItem('user');
this.router.navigate(['login']);
})
}
}
从'@angular/core'导入{Injectable,NgZone};
从“/Webuser”导入{Webuser};
从'@angular/fire/auth'导入{AngularFireAuth};
从'@angular/fire/firestore'导入{AngularFirestore,AngularFirestoreDocument};
从'@angular/Router'导入{Router};
//从“firebase/app”导入*作为firebase;
//导入“firebase/auth”;
@注射的({
providedIn:'根'
})
导出类身份验证服务{
userData:any;//这将保存登录的用户数据
建造师(
公共afs:AngularFirestore,//注入Firestore服务
public afAuth:AngularFireAuth,//注入Firebase身份验证服务
公共路由器:路由器,
公共ngZone:ngZone//ngZone服务被调用以删除范围外的警告
) {
/*在以下情况下将用户数据保存在本地存储中:
登录并在注销时设置null*/
this.afAuth.authState.subscribe(用户=>{
如果(用户){
this.userData=user;
setItem('user',JSON.stringify(this.userData));
parse(localStorage.getItem('user'));
}否则{
setItem('user',null);
parse(localStorage.getItem('user'));
}
})
}
//使用电子邮件/密码登录
登录(电子邮件:字符串,密码:字符串){
使用email和password(电子邮件,密码)返回此.afAuth.signin
。然后((结果)=>{
此.ngZone.run(()=>{
这个.router.navigate(['']);
});
this.SetUserData(result.user);
}).catch((错误)=>{
窗口。警报(错误。消息);
})
}
//使用电子邮件/密码注册
注册(电子邮件:string,密码:string){
返回此.afAuth.createUserWithEmailAndPassword(电子邮件,密码)
。然后((结果)=>{
//这里,当用户注册并返回承诺时,我们调用SendVerificationMail()方法
这是SendVerificationMail();
this.SetUserData(result.user);
}).catch((错误)=>{
窗口。警报(错误。消息);
})
}
//用户注册时发送电子邮件验证
SendVerificationMail(){
返回此.afAuth.currentUser.then(u=>u.sendEmailVerification())
.然后(()=>{
这个.router.navigate(['verify-email-address']);
})
}
//重置忘记的密码
ForgotPasword(密码重置电子邮件:字符串){
返回此.afAuth.sendPasswordResetEmail(passwordResetEmail)
.然后(()=>{
window.alert('密码重置电子邮件发送到您提供的电子邮件。请检查您的收件箱');
}).catch((错误)=>{
窗口。警报(错误);
})
}
//当验证用户电子邮件并登录用户时,返回true
get isLoggedIn():布尔值{
const user=JSON.parse(localStorage.getItem('user'));
返回(user!==null&&user.emailVerified!==false)
}
/*使用用户名/密码登录时设置用户数据,
使用用户名/密码在Firestore数据库中注册
AngularFirestore+AngularFirestore文档服务*/
SetUserData(用户:任意){
const userRef:AngularFirestoreDocument正如错误所说,JSON.parse
接受string
而localStorage.getItems
返回string | null
,因此在解析之前必须检查从localStorage
获取的值是否null
。谢谢,丹尼斯。我已经解决了这个问题。我将这些JSON行从前一行更改为:JSON.parse(localStorage.getItem('user')??“”),并将localStorage.setItem('user',null)更改为localStorage.setItem('user',“”)。这清除了我所有的错误。对我来说,这似乎不是一个好的解决方案,为什么不仅在存在user
的值时解析该值,而不是返回到默认值?此外,'
不是一个有效的JSON值,所以JSON.parse('')
抛出一个错误。@Andrecon-对second Denis说:最好的指导原则是尽早退出(也称为shortcircuit)。如果localStorage中没有“user”项,只需返回false
就可以了。localStorage.setItem('user',null);JSON.parse(localStorage.getItem('user'));当未分配和使用值时,最后一行的用途是什么?无论哪种方式,分解它,首先从存储检查中获取它(如果不是null),然后解析