Posted by bolatah on 7/12/2024, 8:15:26 AM
import { HttpRequest, HttpHandlerFn, HttpHeaders, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { selectAuthToken } from '../selectors/auth.selectors';
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
export const authInterceptor: HttpInterceptorFn = (req: HttpRequest<any>, next: HttpHandlerFn): Observable<HttpEvent<any>> => {
if (req.url.startsWith('http://localhost:9002/todos') || req.url.startsWith('http://localhost:9002/todo')) {
const store = inject(Store);
return store.select(selectAuthToken).pipe(
mergeMap((token) => {
const headers = new HttpHeaders().set('token', `${token}`);
const authReq = req.clone({headers});
return next(authReq);
})
);
} else {
return next(req);
}
};
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideStore } from '@ngrx/store';
import { todosReducer } from './store/reducers/todos.reducer';
import { authReducer } from './store/reducers/auth.reducer';
import { AuthGuard } from './guards/auth.guard';
import { authInterceptor } from './store/interceptors/auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
AuthGuard,
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideAnimationsAsync(),
provideHttpClient(withInterceptors([authInterceptor])),
provideStore({
todos: todosReducer,
auth: authReducer,
}),
],
};