Ways to enable components to access a string dependency token

I'm currently developing an Angular application that utilizes Angular Universal for server-side rendering functionality.

One interesting aspect of my project involves passing a string dependency token as a provider within the providers array in server.ts.

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

The challenge I face relates to accessing the value associated with this token from my components.

After reviewing my app.component.ts, I attempted the following:

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

When checking the terminal, it correctly displays inside app component DELUXE in line with the .env file. However, the browser console yields inside app component null. Why does the value not display in the browser?

If the @Optional() decorator is removed, a

NullInjectionError: No provider for MODEL!
error occurs.

Answer №1

Utilize transfer state to save and retrieve data between the server end and browser. When loading on the browser, fetch the stored data from transfer state.

Upon receiving the data on the server side and printing it, ensure that the data is also stored in transfer state for client-side access. Here is an example of the code:

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)
    }
  } 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the method for dynamically setting the rangeSelector's min and max values multiple times in Angular Highcharts

I'm looking to dynamically set the range of an angular highstock chart by interacting with another component such as a table or button. For example, attempting to use setExtremes for selecting range T1 or T2 does not seem to work properly in this cod ...

The Angular Material Tree component is not rendering properly in an Angular tutorial demonstration

Upon completing the installation of @angular/material, @angular/cdk, and @angular/animations through npm install --save, I attempted to reconstruct the flat tree example provided by Angular. Unfortunately, even after addressing the error message stating Co ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

"I am looking for a way to incorporate animation into my Angular application when the data changes. Specifically, I am interested in adding animation effects to

Whenever I click on the left or right button, the data should come with animation. However, it did not work for me. I tried adding some void animation in Angular and placed a trigger on my HTML element. The animation worked when the page was refreshed, bu ...

Error message "ERR_NO_ICU" appears when trying to run the command "ng serve

I am currently working on a website project using Spring Boot and Angular, but I am encountering some challenges when trying to start Angular's live development server. The error message I receive is the following: ubuntuserver]#> ng serve internal ...

How to Customize the Select Dropdown in Angular Material 2

I am having trouble customizing the default style of this component : https://material.angular.io/components/component/select It contains various classes such as .mat-select-placeholder, .mat-select-value However, I cannot find any information in thei ...

"Create a separate function for the pipeable operator in RXJS for enhanced code

After working on some code, I came up with the following implementation this.form.valueChanges.pipe( take(1), map(val => // doSomething), exhaustMap(val => // someInner observable logic return of({someValue}) ) ).subscrib ...

Transferring pictures between folders

I am currently developing an Angular app that involves working with two images: X.png and Y.png. My goal is to copy these images from the assets folder to a specific location on the C drive (c:\users\images) whose path is received as a variable. ...

Learn how to set up browser targeting using differential loading in Angular 10, specifically for es2016 or newer versions

Seeking advice on JS target output for compiled Angular when utilizing differential loading. By default, Angular compiles TypeScript down to ES5 and ES2015, with browsers using either depending on their capabilities. In order to stay current, I've b ...

Setting the x-api-key header with HttpInterceptor in Angular 4: A guide

I am attempting to use HttpInterceptor to set the header key and value, but I am encountering the following error: Failed to load https://example.com/api/agency: Response to preflight request doesn't pass access control check: No 'Access ...

Issue encountered when populating FormArray with a FormGroup inside a loop in Angular version 17

Encountering an error while trying to populate a FormArray in Angular (version 17): Issue arises at line 44 with the error message: Argument of type 'FormGroup<{ name: FormControl<string | null>; amount: FormControl<number | null>; }&g ...

Tips for transforming a JSON Array of Objects into an Observable Array within an Angular framework

I'm working with Angular and calling a REST API that returns data in JSON Array of Objects like the example shown in this image: https://i.stack.imgur.com/Rz19k.png However, I'm having trouble converting it to my model class array. Can you provi ...

Ways to bounce back from mistakes in Angular

As I prepare my Angular 5 application for production, one issue that has caught my attention is how poorly Angular handles zoned errors. Despite enabling 'production mode', it appears that Angular struggles to properly recover from these errors. ...

When the JSON array is converted into a string, it appears as undefined

Below is a snippet of my service.spec.ts file: service.spec.ts it('should mock the http requests', inject([Service, MockBackend], (service, mockBackend) => { let result:any; mockBackend.connections.subscribe((connection) => { ...

The 'export '__platform_browser_private__' could not be located within the '@angular/platform-browser' module

I have encountered an issue while developing an angular application. Upon running ng serve, I am receiving the following error in ERROR in ./node_modules/@angular/http/src/backends/xhr_backend.js 204:40-68: "export 'platform_browser_private' w ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

Terminate all active service requests and retrieve only the outcomes from the most recent request

Is there a way to cancel ongoing requests and only retrieve the result of the latest request triggered by my service on the backend? Here's my current code: this.vehiclesService.getVehiclesByPage(currentState).subscribe(success => { this.c ...

There was an issue encountered when creating the class: The parameters provided do not correspond to any valid call target signature

I am facing an issue with my code. Here is the scenario: export class MyClass { public name:string; public addr:string; constructor() {} } I have imported MyClass and trying to use it like this: import { MyClass } from './MyClass' ...

Rxjs observables will throw an error if an error occurs and is later caught and returned

Hey there, I'm encountering an issue with the following error message: "you provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable" when trying to make an HTTP request from my effects. delet ...

Exploring the world of Ionic and Angular on Coursera

I've been following a Coursera tutorial, but I've encountered an error. Although I have the code provided by the teacher, it's not working as expected. Unfortunately, I am unsure of what additional code to include since everything seems to ...