Home > Software engineering >  Environment injection to service inside app
Environment injection to service inside app

Time:09-29

By using Nx. Created multiple apps, each app has its own environment with different API URL. Nx Workspace library has some shared services which are using among all apps. But need to pass the environment-api-url when inject the service in the component.

    @Component({
      standalone: true,
      imports: [
       ReactiveFormsModule,
       FormsModule,
       HttpClientModule
      ],
      providers: [AuthenticationService],
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css'],
    })
    export class LoginComponent implements OnInit {
     ngOnInit() {}
    }

Can we pass like this

providers: [AuthenticationService<environment>]

or any other way to achieve it.

advanced appreciated !!

CodePudding user response:

You can create another library called app-config. Then inside create an index.ts file (lib/app-config/src/lib/config/index.ts).

Inside of your index.ts export an InjectionToken.

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

export const APP_CONFIG = new InjectionToken('App Config');

Add this to the Providers of your LoginComponent.

import { APP_CONFIG } from '@YourWorkspaceName/app-config';

providers: [
    {
      provide: APP_CONFIG,
      useValue: environment,
    },
    AuthenticationService
]

Then inside your AuthenticationService inject APP_CONFIG to access your environment variables.

import { APP_CONFIG } from '@YourWorkspaceName/app-config';

    export class AuthenticationService {
     private readonly url: string = this.appConfig.authServiceUrl;
    
     constructor(
        private http: HttpClient,
        @Inject(APP_CONFIG) private appConfig: any
      ) {}
    
     login(EmailAddress: string, Password: string): Observable<any> {
        return this.http.post<{ authToken: string }>(`${this.url}/login`, {
          EmailAddress,
          Password,
        });
      }
    }

Hope you find this helpful.

  • Related