Currently, I am working on a project in Angular and encountering a specific issue.
In my service class, the structure looks like this:
export class AuthService {
authchange: new Subject<boolean>();
private user: User;
registerUser(authData: AuthData) {
this.user = {
email: authData.email,
userId: Math.round(Math.random() * 1000).toString()
};
}
login(authData: AuthData) {
this.user = {
email: authData.email,
userId: Math.round(Math.random() * 1000).toString()
};
}
logout() {
this.user = null;
}
getUser() {
return { ...this.user };
}
isAuth() {
return this.user != null;
}
}
Essentially, there is a custom User object defined within the code:
private user: User;
then there is a method implemented as follows:
logout() {
this.user = null;
}
where an attempt is made to set the object to null upon logging out. However, during compilation, the following error is thrown:
Error: src/app/auth/auth.service.ts:25:9 - error TS2322: Type 'null' is not assignable to type 'User'.
25 this.user = null;
I am currently following a course on Udemy, so the code should be correct according to that.
This is the interface of my User:
export interface User {
email: string;
userId: string;
}
Why is this error occurring? What detail have I overlooked? How can I address this issue?