How to return null in the function returning Observable object

Below method return object of user in first return, in outside return unable to return null.

login (username:any, password:any):Observable<User> {

const credentials={
  "userName":username,
  "password":password
}

this.http.post<User>("https://localhost:5001/api/Person/login",credentials)
.pipe(map(user=>{
  localStorage.setItem('user',JSON.stringify(user));
  this.userSubject.next(user);
  return user;
}));

return null;

}

even I tried Observable<User|null> its not allow to return null type.


Solution 1:

login (username:any, password:any):Observable<User> | null {

But what you're doing doesn't make sense. You should return the observable or make the entire method void. My guess what you're looking for is

login (username:any, password:any) {

    const credentials={
      "userName":username,
      "password":password
    }
    
    this.http.post<User>("https://localhost:5001/api/Person/login", credentials)
    .subscribe(user => {
      localStorage.setItem('user', JSON.stringify(user));
      this.userSubject.next(user);
    }));
}