Home > front end >  Why I cannot set this User object to null in my Angular application?
Why I cannot set this User object to null in my Angular application?

Time:06-13

I am working on an Angular application and I am finding the following problem.

I have a service class 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;
    }
}

Basically I have this custom User object declared:

private user: User;

then I have this method:

logout() {
    this.user = null;
}

wher I try to set this object to null when the logout operation is performed. The problem is that I am obtaining this error at compile time:

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 following a Udemy course so the code should be correct.

This is the code of my User:

export interface User {
    email: string;
    userId: string;
}

Why am I obtaining this error? what am i missing? How can i try to fix it?

CodePudding user response:

This is correct behavior. if you set null in this.user, then your types should be: private user: User | null; or private user?: string;(if you use undefined). Because user can be null.

  • Related