Angular Production and Local parameter

What we want to do

I want to change production and local parameters because I use API URL for production and local development

  • Local (localhost)
  • Production (Actual URL)

environments

Angular app prepares this by default

You can see environments directory under app

environments
|- environment.prod.ts
|- environment.ts

Example

environment.prod.ts

export const environment = {
  production: true,
  baseUrl: 'https://api.specten.com'
};

environment.ts

export const environment = {
  production: false,
  baseUrl: 'http://localhost:8080'
};

How to use this parameter

Use this from Service class to support HttpClient

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class HttpserviceService {

  baseUrl = environment.baseUrl;  // Here

  constructor(private http: HttpClient) { }

  login(data, responseHandle, failureHandle) {
    const httpHeaders = new HttpHeaders({
      'Content-Type' : 'application/json',
    });
    const options = {
      headers: httpHeaders
    };

    this.http.post(this.baseUrl + '/api/test', data, options)
      .subscribe(response => {
        responseHandle(response);
      }, error => {
        failureHandle(error);
      });
  }
}

You can see “import environment” and environment.baseUrl in codes.

コメント