How to access provider value in Angular 18+ using SSR?

Discussão em 'Angular' iniciado por Brandon Taylor, Novembro 25, 2024.

  1. Using Angular SSR, I would like to access a server-side value in my app.component.

    Here is my server-side route:

    app.get('**', (req, res, next) => {
    const { protocol, originalUrl, baseUrl, headers } = req;

    commonEngine
    .render({
    bootstrap,
    documentFilePath: indexHtml,
    url: `${protocol}://${headers.host}${originalUrl}`,
    publicPath: browserDistFolder,
    providers: [
    {
    provide: APP_BASE_HREF,
    useValue: baseUrl
    },
    {
    provide: 'message',
    useValue: 'Message provided server-side'
    }
    ],
    })
    .then((html) => res.send(html))
    .catch((err) => next(err));
    });


    I am providing a value: message

    Here's my component code, where I would like to pick up the message value.

    @Component({
    imports: [
    RouterOutlet,
    ],
    selector: 'app-root',
    styleUrl: './app.component.scss',
    templateUrl: './app.component.html',
    })
    export class AppComponent {

    constructor(
    @Optional()
    @Inject('message')
    readonly message: string,

    @Inject(PLATFORM_ID)
    private readonly platformId: Object,

    private transferState: TransferState,
    ) {
    const MESSAGE_KEY = makeStateKey<string>('message');

    if (isPlatformBrowser(this.platformId)) {
    this.message = this.transferState.get(MESSAGE_KEY, 'Message provided client-side');
    }
    else {
    console.log(this.message); // this value is null

    this.transferState.set(MESSAGE_KEY, this.message);
    }
    }
    }


    message is always null.

    Here's my app.config where I'm specifying client hydration:

    export const appConfig: ApplicationConfig = {
    providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideClientHydration(withEventReplay())
    ]
    };


    What is the correct way to access provided values?

    Continue reading...

Compartilhe esta Página