简体   繁体   中英

What is best practice for coding urls in an angular4 app used in multiple environments?

I have an angular 4 app and I am trying to find a best practices approach to creating a solution for creating a service or some sort of a solution for handling many urls for making http requests in a development as well as a production environment.

My solution at this point looks like this.

import { Injectable } from '@angular/core';
/**
 * PathsService is like a properties file for all of the URL paths used in the application.
 */
@Injectable()
export class PathsService {

  constructor() {}

  productionEnvironment:string = "https://myproductionenvironment.com"
  developmentEnvironment:string = "https://mydevelopmentenvironment.com"

  activeRoot:string = productionEnvironment;


  loginResource = "/loginresources"
  employeeResource = "/employeeresouces"

  public getLoginResources(): string {
    return this.activeRoot+this.loginResource;
  }

  public getEmployeeResource():string {
    return this.activeRoot+this.employeeResource;
  }




}

While I believe this would work fine, there is a small problem because I have to change the activeRoot when switching from development to production environments. I am wondering if there is a better way to do this, so I don't have to manually switch. I could use javascript to take the url, parse it, and switch between production and development environments in that way, but it seems like there should be a better more angular way to solve this issue. Any input on this issue would be greatly appreciated. Thanks!

If you're using the Angular CLI, you have a folder called environments . In this, you have environment.ts and environment.prod.ts .

In both files you have an exported object. In this object, you can add a let apiUrl = 'your URL; . Then, in your files, you import only the first one ( environment.ts )

Then, when you build, you just have to run ng build --prod , and when compiling, instead of using environment.ts , it will use environment.prod.ts

Is that clear enough ?

use angular cli and you'll get environment.dev.ts and environment.prod.ts built at compile time.

for example: http://www.alternatestack.com/development/app-development/angular2-environment-specific-configuration/

If you are using the Angular CLI you should have two files, src/environments/environment.ts and src/environments/environment.prod.ts . In this files you can assign environment variables for your production and development purposes. Just import { environment } from '../environments/environment' and you'll be all set. The CLI will automatically select the right environment for you.

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