Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
set-token.interceptor.ts
@Injectable({ providedIn: 'root' })
export class SetTokenInterceptor implements HttpInterceptor {
constructor(private userService: UserService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (!this.userService.currentUser$.value) {
return next.handle(req);
}
return this.userService.currentUser$.pipe(
first(),
switchMap(user => {
return from(user?.getIdToken() || '');
}),
exhaustMap(token => {
const tenantId = auth().tenantId;
let headers = tenantId
? req.headers.append('Schoolid', tenantId)
: req.headers;
headers = headers.append('Authorization', token);
const authReq = req.clone({ headers });
return next.handle(authReq);
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment