Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type 'null' is not assignable to parameter Angular

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
    private currentUserSubject: BehaviorSubject<User>;
    public currentUser: Observable<User>;

    constructor(private http: HttpClient) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
    }

    public get currentUserValue(): User {
        return this.currentUserSubject.value;
    }

    login(username: string, password: string) {
        return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password })
            .pipe(map(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify(user));
                this.currentUserSubject.next(user);
                return user;
            }));
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
    }
}

Any idea why am i getting error at the last line(this.currentUserSubject.next(null))? Error message: Argument of type 'null' is not assignable to parameter of type 'User'. The latest typescript version does not allow this? What would be another solution?

like image 365
Szocs Arnold Avatar asked Mar 01 '26 06:03

Szocs Arnold


2 Answers

Typescript became stricter.

You can either turn off strict mode or make your observable accept nulls:

private currentUserSubject: BehaviorSubject<User | null>;
like image 119
Andrei Avatar answered Mar 02 '26 20:03

Andrei


check if this.currentUserSubject.next(null); is really required

like image 45
sanjeevRm Avatar answered Mar 02 '26 19:03

sanjeevRm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!