How to change URLs automatically in services, afte

2020-02-07 06:37发布

We are hosting a new application with angular 6 and we have many servers with diff URLs, i want to change them automatically(like .property file in java). after searching in google i got some answers like changing paths in environment.ts file, so it will affect to all components. but its not exactly my requirements, means if i change URL in environment.ts file, we should save the file and we need to compile it once again. So exactly this is the problem i am facing, i don't want to save / compile the file.

Please help me in this situation.

service.ts file.

emplLoginCheckUrl = this.baseUrl+"/checkValidUser";

i tried to change base url from environment.ts file, its working correctly but after saving the file, i dont want want save file it should change automatically.

.service.ts file.

 emplLoginCheckUrl = this.baseUrl+"/checkValidUser";

       validateUserDetails(employeeDetails): Observable<any> {
            console.log(this.baseUrl);
            return this._httpClinet.post(this.emplLoginCheckUrl, employeeDetails);
        }

environment.ts file.

export const environment = {
  production: false,
  baseUrl: "http://rest/somerestservice"
};

Expected:

URLs should change automatically without saving/running/compiling/building again and again, because only one time I can do saving/running/compiling/building while hosting. after hosting if I want to change URLs I can't go there, change the path and cant compile it once again.

3条回答
虎瘦雄心在
2楼-- · 2020-02-07 06:46

You could pass the endpoint in as a query parameter when accessing the application for the first time like this:

http://localhost/yourapplication?baseUrl=http://rest/somerestservice

and then read this query parameter value in your app.component.ts and set it to the baseUrl environment variable.

Beware even though this would work, I don't know if this would be the most elegant way to achieve this.

Update: As OP requested code

Demo: https://angular-sku9xx.stackblitz.io/?baseUrl=http://rest/somerestservice

Code for the demo: https://stackblitz.com/edit/angular-sku9xx?file=src/app/app.component.ts

查看更多
\"骚年 ilove
3楼-- · 2020-02-07 06:51

This is basically the "well known file" pattern. It's a path on a web server that exposes config information. The applications have to fetch the live config via a HTTP request while they are bootstrapping, and can refresh the config by re-fetching the data.

https://ma.ttias.be/well-known-directory-webservers-aka-rfc-5785/

It's based on an IETF RFC:

https://tools.ietf.org/html/rfc5785

查看更多
唯我独甜
4楼-- · 2020-02-07 06:59

This is a common scenario for the Angular application.
That is, you don't want to build and compile again the code on the server, if you want to change backend api url. Following is the approach that i use with my Angular projects.

Approach :

1. Create a config.json file in the assets folder, as assets folder is present on the server.

{  // ---------- config.json---------
  "serviceUrl": "http://172.168.1.190:1393/"
}


2. Create a variable serviceUrl in your constants file, as you will have a constant file for your angular application. Assign this variable empty value as this variable will keep the updated service url later.

export class AppConstants { 

  public static xhr = {
        url: {
                serviceUrl: ''  // <===== empty value
             }
       }
}


3. Implement APP_INITIALIZER to read the config.json file at the application start up. And read the value of serviceUrl from config.json and assign this value to the same variable present in the constants file.

   {   // in app.module.ts providers
      provide: APP_INITIALIZER,
      useFactory: ConfigurationServiceFactory,
      deps: [ConfigService],
      multi: true
    }
---------------------------------------------------
// ConfigurationServiceFactory which is used at App initialization
export function ConfigurationServiceFactory(configService: ConfigService) {
return () => configService.load();
};
---------------------------------------------------
// this method is called at application start up
// and config.json file is read here, and the service url from
// constant file is replaced by the value provided in the assets's config.json
load() {
const configUrl = '~/../assets/config.json';
    return new Promise((resolve) => {
        this.http.get(configUrl)
        .toPromise()
        .then((config: any) => {
            this.config = config;
            console.log('Configurationd fetched  : ', this.config);
            //----- variable is updated now with new value from the file -------
            AppConstants.xhr.url.serviceUrl = this.config.serviceUrl;
            resolve(true);
        })
        .catch( (err) => console.log(err));
    });
}
  1. For every HTTP call, use the constants file's serviceUrl as the base url.

    this.http.get('${AppConstants.xhr.url.serviceUrl}api/roles/list')

  2. As changing variable value in assets folder config.json will be fetched at start up and will replace the constant file variable, which we will be using for apicalls.

App Initializer code with config.json file (for referrence)

查看更多
登录 后发表回答