angular-architects / module-federation-plugin

MIT License
718 stars 194 forks source link

HTTP_INTERCEPTOR inside remote MFE #577

Open frazzaglia opened 3 months ago

frazzaglia commented 3 months ago

Hi! How can I instantiate an HTTP_INTERCEPTORS inside my MFE? I would for instance a ProxyInterceptor which works only when a mfe is loaded throug loadRemoteModule. Thanks.

3myr commented 3 months ago

Hi,

Here's an example of a service that uses HTTP_INTERCEPTORS inside a MFE:

api.service.ts:

import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS, HttpClient, provideHttpClient, withInterceptorsFromDi} from '@angular/common/http';
import {Observable} from 'rxjs';
import {AuthInterceptor} from "../interceptor/auth.interceptor";

@NgModule({
    providers: [
        provideHttpClient(
            withInterceptorsFromDi()
        ),
        {
            provide: HTTP_INTERCEPTORS,
            useClass: AuthInterceptor,
            multi: true
        }
    ]
})
export class ApiService {
    constructor(private http: HttpClient) {
    }

    public get(url: string): Observable<any> {
        return this.http.get(url);
    }

    public post(url: string, data: any): Observable<any> {
        return this.http.post(url, data);
    }
}

auth.interceptor.ts:

import {Injectable} from '@angular/core';
import {HttpInterceptor, HttpRequest, HttpHandler, HttpEvent} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log("Interpect http request")

        // Get the token (e.g., from localStorage)
        const authToken = '1234' // localStorage.getItem('authToken');

        // Clone the request and add the token
        const authReq = request.clone({
            headers: request.headers.set('Authorization', `Bearer ${authToken}`)
        });

        // Send the modified request
        return next.handle(authReq);
    }
}

You can use this implementation in a Standalone component by passing the service into the Imports

button.component.ts

@Component({
    selector: 'app-button',
    standalone: true,
    imports: [ApiService],
    templateUrl: './button.component.html',
    styleUrl: './button.component.scss'
})
export class ButtonComponent {
  constructor(private apiService: ApiService) {}
}
frazzaglia commented 3 months ago

Hi @3myr, thank you for reply but I've already tried your solution and it does not work when I load my mfe through loadRemoteModule in my shell application.

Your solution works only when I work directly on my mfe. Do you have any other ideas? Thanks.