Home > Net >  Angular - argument of type null is not assignable to parameter of type IUser
Angular - argument of type null is not assignable to parameter of type IUser

Time:12-24

In my Angular-13 project I have this model interface:

export interface IUser {
   email: string;
   token: string;
}

And also this service:

export class AccountService {
  baseUrl = environment.apiUrl;
  private currentUserSource = new ReplaySubject<IUser>(1);
  currentUser$ = this.currentUserSource.asObservable();

  constructor(private http: HttpClient, private router: Router) { }

  loadCurrentUser(token: string) {
    if (token === null) {
      this.currentUserSource.next(null);
      return of(null);
    }
    let headers = new HttpHeaders();
    headers = headers.set('Authorization', `bearer ${token}`);

    return this.http.get(this.baseUrl   'account', {headers}).pipe(
      map((user: IUser) => {
        if (user) {
          localStorage.setItem('token', user.token);
          this.currentUserSource.next(user);
        }
      })
    );
  }
}

However, I got this error:

argument of type null is not assignable to parameter of type IUser

and null is highlighted in:

this.currentUserSource.next(null);

How do I get this resolve?

Thanks

CodePudding user response:

ReplaySubject.next() is expected to receive parameter with T value.

next(value: T): void

Parameters

value Type: T.

Returns void

which T is IUser based on below statement:

private currentUserSource = new ReplaySubject<IUser>(1);

Solution

You can resolve it by declaring currentUserSource as ReplaySubject<IUser | null> type.

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

Sample Demo on StackBlitz

  • Related