2

I'm learning about DI-based interceptors in Angular 20. When I ran my Angular app, the home page (that contains API to get products) was loading for a long time and I received no response on the browser.

I tried to add method withInterceptorsFromDi() into provideHttpClient() and provide interceptor class into app.config.ts, but I just received the same result.

interceptor:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { TokenService } from "../service/token.service";

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    constructor(private tokenService: TokenService) { }

    intercept(
        req: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        debugger
        const token = this.tokenService.getToken();
        if (token) {
            req = req.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`,
                }
            });
        }
        return next.handle(req);
    }
}

app.config.ts:

import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS, provideHttpClient, withFetch, withInterceptorsFromDi } from '@angular/common/http';
import { TokenInterceptor } from './interceptors/token.interceptors';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideClientHydration(withEventReplay()),
    provideHttpClient(
      // withFetch(),
      withInterceptorsFromDi(), // Enable DI-based interceptors
    ),
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true,
    }
  ]
};

service to call getProducts api:

import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { HttpUtilService } from './http.util.service';
import { Product } from '../models/product';

@Injectable({
    providedIn: 'root'
})
export class ProductService {
    private apiGetProducts = `${environment.apiBaseUrl}/products`;

    constructor(private http: HttpClient, private httpUtilService: HttpUtilService) {

    }

    getProducts(page: number, size: number): Observable<Product[]> {
        const params = new HttpParams()
            .set('page', page)
            .set('limit', size);
        return this.http.get<Product[]>(this.apiGetProducts, { params });
    }
}

Updated: (From Naren Murali requests)

app.component.ts:

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { HomeComponent } from './components/home/home';
import { OrderComponent } from './components/order/order';
import { OrderConfirmComponent } from './components/order-confirm/order-confirm';
import { LoginComponent } from './components/login/login';
import { RegisterComponent } from './components/register/register';
import { DetailProductComponent } from './components/detail-product/detail-product';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [
    RouterOutlet,
    HomeComponent,
    // OrderComponent,
    // OrderConfirmComponent,
    // LoginComponent,
    // RegisterComponent,
    // DetailProductComponent,
    // FormsModule
  ],
  templateUrl: './app.html',
  styleUrl: './app.scss'
})
export class App {
  protected title = 'shopapp-frontend';
}

"Whether your app use SSR?" -> Yes, I have seen it in the app.routes.server.ts:

import { RenderMode, ServerRoute } from '@angular/ssr';

export const serverRoutes: ServerRoute[] = [
  {
    path: '**',
    renderMode: RenderMode.Prerender
  }
];

Update:

I added my repo link. If you have time, please help me to check

  • Frontend: Angular, bootstrap
  • Backend: Springboot
  • Database: MySQL

https://github.com/deadofhead123/shopapp.git

Update:

From Naren Murali's question, I created a new Angular project without using SSR and the project have worked successfully. Thanks for all your help.

2
  • you never shared app.component.ts and whether your app uses SSR? Could you delete your previous question Commented Aug 29 at 8:22
  • is your repo public could you share github repo? if not please share the app.html and home component details Commented Aug 29 at 10:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.