Reputation: 342
For my Angular project I have multiple environments, each for a particular DTAP stage. When building this Angular project I set the --base-href flag to the corresponding base URL. However, I also have a URL set in my code which belongs to a second web server to correspond with. This web server also has multiple DTAP stages. So, I would like to be able to 'know' in my code which --base-url flag value is set to be able to set a variable to the corresponding URL of the second web server.
Since I could not find anything on this subject I have been unable to achieve any successes. For now I have it set up so that I have to manually change the variable's value. But I want to get rid of that practice since it is easily forgotten when building the project.
The idea is to have to following code:
let url;
if (base-href.contains('test'))
url = 'https://test.com';
else if (base-href.contains('acceptance'))
url = 'https://acceptance.com'
else if (base-href.contains('deployment'))
url = 'https://deployment.com'
// Send API call to URL
The URLs I use to build with are fixed, so I know what text will be in them so that I can ensure that the URL for the second web server is always set correcly.
If anybody could point me in the right direction to achieve this that would be greatly appreciated!
Upvotes: 0
Views: 278
Reputation: 8131
You can add another variable to your environment.ts
.
when you compile, that value will be set per environment, allowing to reference that variable in your code.
export const environment = {
production: true,
host: 'test'
};
in your component:
import { environment } from '../environments/environment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
if (environment.host == 'test') {
// whaever
}
}
}
a better approach would be, to invoke an http request when the app loads, to fetch a plain json file / db record, holding those settings at the server. that way you can copy-paste your test-proven code, straight to production, excluding the json file, and it just works.
read more at: Dave M Bush's article - where-to-store-angular-configurations
Upvotes: 1