Search code examples
angularangular-universalangular-dependency-injection

How to make a string dependency token accessible to components?


I'm building an Angular app that uses Angular universal for server-side rendering.

I got a string dependency token being passed as a provider in the providers array of server.ts

providers: [{ provide: 'MODEL', useValue: process.env.API_MODEL }]

The value associated with this token, how do I make it accessible to my components?

If I head into my app.component.ts and do:

export class AppComponent {
    constructor(@Optional() @Inject('MODEL') private model: string) {
        console.log('inside app component', this.model)
    }
}

In my terminal, it prints inside app component DELUXE which is expected since that's what's stored in the .env file. However, when I check out the console in the browser it says inside app component null. Why isn't the value showing up in the browser?

If I get rid of the @Optional() decorator I get a NullInjectionError: No provider for MODEL! error.


Solution

  • Save The data to the server end using transfer state. And once you load on the browser you can fetch the data from transfer state.

    The server side receives the data and prints it but in order to have that data on the client you must store it transfer state. The code shall be like

    constructor(
        @Optional() @Inject('MODEL') private model: string,
        @Inject(PLATFORM_ID) private _platformId: Object,) {
    }  
    
    ngOnInit(): void {
        if (isPlatformServer(this._platformId)) {
              this.transferState.set(makeStateKey('model'), this.model);
        } else if (isPlatformBrowser(this._platformId)) {
              this.model= this.transferState.get(makeStateKey('model'), null)
        }
      }