How to use a dynamic url in angular projects 6

-3

Now I need to send to homologate my project, created in Angular 6. I have a file called app.constants and inside a class called Configuration. In this class "chumbei" the API url for my tests, type: link . Well, now I need to stop. The colleague told me to read about Environment. I am reading, but I have not been able to abstract the concept. This is the way? Anyone have any tips to give?

    
asked by anonymous 03.08.2018 / 21:48

2 answers

0

I found this documentation here.

Basically, you can declare variables whose values change with the environment, just create a constant in the files that define those environments, and reference those constants in the code.

That is, in the development environment, you would have something like

export const environment = {
  production: false,
  apiUrl: 'sua URL para desenvolvimento'
}

And then just import the constant and use its values where you need it

import { environment } from 'caminho/para/environment';
// Indo para onde interessa
usandoVariavelEnvironment() { console.log(enviroment.apiUrl); }
    
03.08.2018 / 22:04
0

The Environment is for you to define your variables that change between development and production

They work very simply, they are two files, environment.ts for development and environment.prod.ts for production, in them you export an object that will contain the data, these two objects must have the same keys but with different values, for example

environment.ts :

export const environment = {
  production: false,
  api: 'localhost:3000'
}

environment.prod.ts :

export const environment = {
  production: true,
  api: 'api.example.com'
}

To use just import the file and use the properties of the exported object:

import { Component } from '@angular/core';
//A url é essa, não coloque '.ts' ou '.prod.ts'
import { environment } from './../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(environment);
  }
}

When you are in development environment (% with%) Angular will use the file ng server , with the production build ( environment.ts ) it will use ng build --prod

    
03.08.2018 / 22:54