Rahul
Rahul

Reputation: 121

In Angular how to Create a Configurable Property file to read a property, in production environment?

In my application, I have created appMessages.ts, which holds a variable like:

export const appMessages = {
    my_url: 'http://localhost:8080/myApp',
}

I`m basically using this to make REST calls. In real production environment, The variable value keeps changing, and needs to be configurable. If I use appMessages.ts, and create a production bundle, using

ng build --prod

Problem is, appMessages.ts is not configurable anymore. Is there an Angular way to create a configurable property file, which can be configured dynamically with 'my_url' depending on the current development environment?

Can some kind of property file, which can be read after the product has been deployed?

Upvotes: 1

Views: 5406

Answers (1)

Spithas
Spithas

Reputation: 381

You can create the following config.json in the src directory and then use the APP_INITIALIZER provider.

{
    "myUrl": "http://172.22.251.207:20235"
}

app.module.ts

...
export function initConfig(config: AppConfigService) {
  return () => config.load();
}
...
providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initConfig,
      deps: [AppConfigService],
      multi: true
    }]
...

app-config.service.ts

@Injectable({
    providedIn: 'root'
})
export class AppConfigService {
    private config: Config = null;
    public configSubject: Subject<any> = new Subject<any>();

    constructor(private http: HttpClient) { }

    public load() {
        return this.http.get(environment.deployUrl + 'config.json')
            .toPromise()
            .then((config: any) => {
                this.config = config;
                this.configSubject.next(this.config);
            })
            .catch((err: any) => {
                console.error('ERROR: ' + err);
            })
    }

    getMyUrl() {
        return this.config.myUrl;
    }
}

export class Config {
    myUrl: string;
}

Upvotes: 3

Related Questions