How to use a dynamic url in angular projects 6

Asked

Viewed 596 times

-3

I now need to send my project, created in Angular 6, to Homolog. I have a file called app.constants and inside a class called Configuration. In this class I "failed" the API url for my tests, like: http://localhost:4200. Well, now I need not fail anymore. The colleague told me to read about Environment. I’m reading, but I still could not abstract the concept. Is this the way? Does anyone have any tips to give?

  • 2

    So "deschumbe"!

  • The URL will be informed by the user ? In this case, configured.

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 these environments, and reference these 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 them

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

0

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 (ng server) Angular will use the file environment.ts, with the production build (ng build --prod) he will use the environment.prod.ts

Browser other questions tagged

You are not signed in. Login or sign up in order to post.