Issue
I work on my app locally, but after some task completed I deploy it on netlify to check how it goes.
I want to switch my fetch requests depending on where I serve the app (local/netlify)
Here is my auth.service.ts, which logic should I implement ?
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const baseUrl = 'http://localhost:3001'
const deployedUrl = 'https://my-deployed-server.herokuapp.com'
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
login(user:any){
return this.http.post(`${baseUrl}/login`, user, {observe: "body", responseType:"json"})
}
signup(user:any){
return this.http.post(`${baseUrl}/signup`, user, {observe: "body", responseType:"json"})
}
}
Thank for your helps
Solution
You should create different .env
files. In your project you should have folder named enviorment
inside that folder you should have at least two files: environment.ts
and environment.prod.ts
(you can add as many environment files as you like). Inside those files you can declare different variables. So in your case you have to create one more env
files (i will assume that the heroku version will be your production enviorment).
// File environment.prod.ts
export const environment = {
production: true,
api: 'https://my-deployed-server.herokuapp.com'
};
// File environment.dev.ts
export const environment = {
production: true,
api: 'localhost:{your-port here}'
};
after that in your service you will use env files as so
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { enviorment } from 'environments/environment'
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
login(user:any){
return this.http.post(`${enviorment.apiUrl}/login`, user, {observe: "body", responseType:"json"})
}
signup(user:any){
return this.http.post(`${enviorment.apiUrl}/signup`, user, {observe: "body", responseType:"json"})
}
}
Here the important thing is that you should import the environment
variable from the base environment
file (not .prod , .dev paths). Based on your build config the base environment file will be overwritten with some of the other environment files. So if you build/serve your app for production the apiUrl
will point to the remote server and if you build/serve for dev, the apiUrl
will be localhost
You can learn more about the file replacement here and about the build configurations here