0

I have an ordinary problem, when I build my angular project in development mode and copy dist files into server folder, when changed server url I can't find endpoint url to change it and I have to rebuild my project with new endpoint url.

How can I define endpoint of webapi's in external file to be dynamically in the future, for typically I store it in environment.prod.ts like bellow

export const environment = {
    production: true,
    serverBaseUrl: 'http://example.com'
};

and call in service files with command this.http.get(environment.serverBaseUrl + '/api/...')

Mohammad
  • 921
  • 7
  • 15

1 Answers1

3

This is possible, but not the right way I think.

a) If you are using containers and mircroservice, it's a good idea to have relative urls like '../api-service/login'. If this api has not the same root, you can set up a proxy or load balancer.

b) Another way is to set a placeholder serverbaseUrl: 'xxxxxx', The deploy-script can replace xxxxxx in the compiled min.js files. I don't like this way, but it works fine.

c) It's possible to put a json config file in the asset folder assets/config/urls.json. This can be load at startup (app component). These urls can be set to each service via static forRoot(). forRoot must be implemented by you.
AppComponent constructor:

authAjaxService.forRoot(theJsonResponse);

and

@Injectable()
export class AuthAjaxService {

private static readonly config = {
    loginUrl: 'assets/mock-data/auth/login.json',
    logoutUrl: 'assets/mock-data/auth/logout.json',
};

static forRoot(config) {
    Object.assign(this.config, config);
}

login(loginData: LoginRequestData): Observable<LoginResponseData> {
   const url = AuthAjaxService.config.loginUrl;
   return this.http.post<LoginResponseData>(url, loginData);
}
...

c) will make the startup of your app slower, because you need an ajax call to get the config.

Marc
  • 1,836
  • 1
  • 10
  • 14