Reputation: 1057
In my Angular-13, I have this code:
export class AuthService {
baseUrl = environment.apiUrl;
private currentUserSource = new ReplaySubject<IUser | null>(1);
currentUser$ = this.currentUserSource.asObservable();
...
}
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>
{
let currentUser: IUser;
this.authService.currentUser$.pipe(take(1)).subscribe(user => currentUser = user);
if(currentUser!){
request = request.clone({
setHeaders:{
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
I got this error:
Type 'IUser | null' is not assignable to type 'IUser'
currentUser is highlighted in user => currentUser = user)
How do I resolve this?
Thanks
Upvotes: 1
Views: 140
Reputation: 6250
The issue is that the type of your variable currentUser
is IUser
and it is been assined the value from currentUser$
, which I believe has the type Observable<IUser | null>
To fix it replace line
let currentUser: IUser;
with
let currentUser: IUser | null;
or make sure the type of currentUser$
is Observable<IUser>
Upvotes: 2