2
@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?

4 Answers 4

7

Typescript became stricter.

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

private currentUserSubject: BehaviorSubject<User | null>;
Sign up to request clarification or add additional context in comments.

3 Comments

How can I turn off the strict?
find strictNullChecks in tsconfig and set it to false
Don't turn off strict mode, it's here for a reason: save you from errors at runtime!
1

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

Comments

1

the best practice is you use always <User| null>

example private currentUserSource = new ReplaySubject<User | null>(1);

then you can call that function in this.currentUserSource.next(null); or the easiest is

private currentUserSource = new ReplaySubject(1);

then this.currentUserSource.next(); () can consider as null

Comments

0

Juts use it like:

this.currentUserSubject.next();

or

this.currentUserSubject = new BehaviorSubject<User | null>(JSON.parse(localStorage.getItem('currentUser')));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.