angularfirebase-authentication
angularfirebase-authentication copied to clipboard
TS error: Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'
I got this error while building an angular app. The error message I am getting: argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'. It has to do with the localStorage methods ie (setItem() and getItem())
I have checked so many examples and I don't see where I am wrong but I keep getting this same error. My code is below:
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 localstorage 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')); // error is this very line
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user')); // Another error
}
})
}
// 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()) <= error with the (u.sendEmailVerification(). It say u is possibly null .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')); <= error here again 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']);
})
}
}
What am i doing wrong?``
@andrejonn31 maybe this will help JSON.parse error
I'd say the best solution would be to change it to the following:
JSON.parse(localStorage.getItem('user') || '{}');