简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM