Sahil
Sahil

Reputation: 1413

What's the correct way to setup different URL prefix in production and development environment?

How do you setup different URL Prefix in production and development environment? So during development and production there are different domains that are being hit, how do you dynamically switch between two differnt hosts?

This is what I am doing right now.

environment.ts

export const environment {
    production: true
}

export const DEVELOPMENT_API_PREFIX = 'http://localhost:55403/api/v1';
export const PRODUCTION_API_PREFIX = 'http://example.com/api/v1';

login.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment, PRODUCTION_API_PREFIX, DEVELOPMENT_API_PREFIX } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  API_PREFIX: string;

  constructor(private http: HttpClient) { }

  loginUser(username: string, password: string) {
    if (environment.production) {
      this.API_PREFIX = PRODUCTION_API_PREFIX;
    } else {
      this.API_PREFIX = DEVELOPMENT_API_PREFIX;
    }

    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);
    return this.http.post(this.API_PREFIX + 'login', formData);
  }
}

Now the problem with this setup is, that I have to go write an IF statement in a every service. Just wanted to know which is a better way of doing things.

Upvotes: 0

Views: 809

Answers (1)

Kenany
Kenany

Reputation: 562

One of most solution is to create environment.[env].ts file for each environment. for exemple for production, create environment.prod.ts file. So you can use the same key in this new config file. For exemple:

in environment.prod.ts

API_PREFIX: 'http://xxx'

in environment.ts

API_PREFIX: 'http://xxx

Now open your angular.json file, find the configurations section then process the replacement:

"production": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }

then just import the API_PREFIX

import { environment, API_PREFIX } from '...';

You can follow this link for most explanations: https://www.jvandemo.com/how-to-use-environment-variables-to-configure-your-angular-application-without-a-rebuild/

Upvotes: 1

Related Questions