Sending server-side data to Angular2 initialization process

I need help with getting data from my server into the Angular2 startup process. I want to configure HTTP headers for every request by using custom request options, but the header values come from my backend server.

Here’s my current index.ts setup:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { MainComponent } from "./main.component.ts";

platformBrowserDynamic().bootstrapModule(MainComponent);

I know how to send data to the main component after it starts, but I need access to server data during the bootstrap phase itself. How can I make this work?

Here’s my build configuration:

module.exports = {
  entry: {
    main: "./src/app/index.ts"
  },

  output: {
    filename: "./dist/[name].bundle.js"
  },

  resolve: {
    extensions: [".ts", ".js"]
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'typescript-loader'
      }
    ]
  }
};

Any suggestions would be really helpful!

interesting challenge! have u tried the APP_INITIALIZER provider? it runs async ops b4 the app loads. what server data do u need - auth tokens or config settings? how complex is your setup?

another way is to leverage Angular’s env files for build-time replacement. fetch server config while building and inject it into environment.ts. works if your header values are stable, but won’t support truly dynamic runtime config.

Just inject the server-side config directly into your HTML template before Angular starts up. Add a script tag in your server-rendered HTML that creates a global config object with your header values. In index.html, do something like window.serverConfig = { headers: { ... } } and grab it during Angular initialization. This way the data’s available right away without extra HTTP requests that’ll slow down your app launch. I’ve used this pattern tons of times for auth tokens and API endpoints that need to be set before any HTTP interceptors kick in.