1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

angular 17 SSR lazyloading modules not working

Discussão em 'Angular' iniciado por sahar omidi, Setembro 14, 2024.

  1. sahar omidi

    sahar omidi Guest

    after update my angular app from version 10 to version 17, i add SSR using @nguniversal/express-engine and express to this project and it work in build and run ssr on port 4000 , but when i navigate to routes all pages ssr not working . my angular app is using lazyloading module and i create log in server.ts only log is c created for / route and in other route not working . my app not have any error in server ts log, when i check viewSource the content is not showing as html in viewsource , how to fix it ?

    this is my serverRouting :

    import {NgModule} from '@angular/core';
    import {RouterModule} from '@angular/router';
    import {routes} from './app-routing.module';


    @NgModule({
    imports: [RouterModule.forRoot(routes, { initialNavigation: 'enabledBlocking' })],
    exports: [RouterModule]
    })
    export class AppServerRoutingModule {

    }



    and

    route in appRouting :

    import {NgModule} from '@angular/core';
    import {RouterModule, Routes} from '@angular/router';
    import {ErrorNotFoundComponent} from './error-pages/error-not-found/error-not-found.component';

    export const routes: Routes = [
    {
    path: '',
    loadChildren: () =>
    import('./layouts/layout.module').then((m) => m.LayoutModule),
    },
    {
    path: 'landing',
    loadChildren: () => import('./modules/landing/landing.module').then((m) => m.LandingModule)
    },
    {path: '404', component: ErrorNotFoundComponent},
    {path: '**', redirectTo: '/404'}
    ];

    @NgModule({
    imports: [
    RouterModule.forRoot(routes, {
    useHash: true,
    scrollPositionRestoration: 'top',
    anchorScrolling: 'enabled',
    scrollOffset: [0, 150]
    }),
    ],
    exports: [RouterModule],
    })
    export class AppRoutingModule {
    }


    and my server.ts file is :

    import 'zone.js/node';
    import { join } from 'path';
    import { ngExpressEngine } from '@nguniversal/express-engine';
    import express from 'express';
    import { AppServerModule } from './src/main.server';

    export function app(): express.Express {
    const server = express();
    const distFolder = join(process.cwd(), 'dist/JustyBookWebApp/browser');
    const indexHtml = join(distFolder, 'index.html');

    server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
    }));

    server.set('view engine', 'html');
    server.set('views', distFolder);

    server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
    }));

    server.get('*', (req, res) => {
    console.log('Rendering request for URL:', req.url);

    res.render(indexHtml, { req }, (err, html) => {
    if (err) {
    console.error('Rendering request Error:', err);
    res.status(500).send('Server Error');
    } else {
    res.send(html);
    }
    });
    });

    return server;
    }

    function run(): void {
    const port = process.env.PORT || 4000;
    const server = app();
    server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
    });
    }

    run();


    and my TransferHttpResponseInterceptor:

    import {isPlatformBrowser, isPlatformServer} from '@angular/common';
    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
    import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
    import {makeStateKey, TransferState} from '@angular/platform-browser';
    import {tap} from 'rxjs/operators';
    import {RequestKeyExtractorService} from './request-key-extractor.service';
    import {Observable, of} from 'rxjs';

    const STATE_KEY_PREFIX = 'http_requests:';

    @Injectable()
    export class TransferHttpResponseInterceptor implements HttpInterceptor {
    constructor(
    private transferState: TransferState,
    private requestKeyExtractor: RequestKeyExtractorService,
    @Inject(PLATFORM_ID) private platformId: object // Change to Object for PLATFORM_ID
    ) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Interceptor - Platform:', this.platformId);
    console.log('Interceptor - Request Method:', req.method);
    console.log('Interceptor - Request URL:', req.url);
    // Nothing to do with non-GET requests
    if (req.method.toUpperCase() !== 'GET') {
    return next.handle(req);
    }

    const key = makeStateKey<HttpResponse<object>>(STATE_KEY_PREFIX + this.requestKeyExtractor.getKey(req));
    console.log(`key is ${key}`);
    if (isPlatformBrowser(this.platformId)) {
    console.log(`is browser platform`);
    // Try reusing transferred response from server
    const cachedResponse = this.transferState.get(key, null);
    if (cachedResponse) {
    this.transferState.remove(key); // using transferred state should be used for the very first time
    return of(new HttpResponse({
    body: cachedResponse.body,
    status: 200,
    statusText: 'OK (from server)',
    }));
    }
    return next.handle(req);
    }

    if (isPlatformServer(this.platformId)) {
    console.log(`is server platform`);
    console.log(`key is ${key}`);
    // Try saving response to be transferred to browser
    return next.handle(req).pipe(tap(event => {

    if (event instanceof HttpResponse && event.status === 200) {
    // Update the cache.
    const response = {
    body: event.body
    };

    this.transferState.set(key, response);
    }
    }));
    }

    // Add a fallback return statement to ensure all code paths return a value
    return next.handle(req); // Handles the case where the platform isn't recognized
    }
    }



    and my main.server.ts is :

    /***************************************************************************************************
    * Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
    */
    import '@angular/localize/init';

    import {enableProdMode} from '@angular/core';

    import {environment} from '@env/environment';

    if (environment.production) {
    enableProdMode();
    }

    export {AppServerModule} from './app/app.server.module';

    Continue reading...

Compartilhe esta Página