简体   繁体   中英

make condition on environment.prod.ts file

enter image description here

How could I make the condition in below code and environment.ts file.

export const environment = {
  production: true,
  if(our condiion = "impdev.something.com"){
   API_url:'https://impdev.something.com/Angular',
  }
  if(our condiion = "dev.something.com"){
    API_url:'https://dev.something.com/Angular',
  }
  if(our condiion = "app.something.com"){
    API_url:'https://app.something.com/Angular',
  }

};

idk if it's what you want, but in angular.json ctrl + f to search for fileReplacements , in here you can tell Angular which environment folder file to replace with which under the different modes.. then you can access the same variable in environment.ts though your whole app, and it will be replaced automatically depending on your serve or build setups.

if unsure, just copy-paste the whole "production" JSON tha tcointains the fileReplacements property, and change the replace value with a new environment.ts file that you created (as in environment.dev.ts ) and then copy all the variables from one environment to another and change values, and use them through the app

You will achieve this in other way using following solution.

environment.ts

export const environment = {
  production: true,
  dev: { serviceUrl: 'https://dev.something.com' },
  stage: { serviceUrl: 'https://stage.something.com' },
  prod: { serviceUrl: 'https://prod.something.com' },
  local: { serviceUrl: 'http://localhost:8080/' },
};

NetworkService.ts

export class NetowrkService {

  url: string;
  env: string
  constructor(private http: HttpClient) {
    this.env = this.setENV();
    this.url = environment[this.env].serviceUrl;
  }

  setENV() {
    if (window.location.hostname.indexOf("dev") != -1) {
      return "dev";
    } else if (window.location.hostname.indexOf("stage") != -1) {
      return "stage";
    } else if (window.location.hostname.indexOf("localhost") != -1) {
      return "local";
    } else {
      return "prod";
    }
  }


   // Call rest API
}

You can use ternary operator here,

export const environment = {
  production: true,
  API_url: your_condition_here ? '' : '';
};

But from where you will get the condition here?

Main.ts

if (environment.production) {
  enableProdMode();
}

environment.ts

export const environment = {
  production: false,
  animal: '🐊'
};

environment.prod.ts

export const environment = {
  production: true,
  animal: '🐔'
};

app.component.ts

import { Component } from '@angular/core';
import { environment } from '../environments/environment';

@Component({ ... })
export class AppComponent {
  animal: string = environment.animal;
}

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