Alan
Alan

Reputation: 43

I want to change the route of Laravel's api using Angular

I work with Angular for the frontend and Laravel's api for the backend.

When I'm developing a project, I have to set the route of laravel to localhost:8000/api to be able to do POST, GET, etc

Then when I'm done, I have to change the route to the one on the host page backend-folder/public/api

I use a service that is used so that all requests have the same base route

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class PathService {
  constructor() {}

  DataBasePath() {
    return '/backend-folder/public/api';
    // return 'http://localhost:8000/api';
  }
}

The problem is that I always have to be changing the path when I'm developing it and when I have to deploy, sometimes I forget to do that and I have to build again with Angular

Is there a way that when I'm developing the path it's localhost:8000/api and when I deploy (ng build) the path changes to backend-folder/public/api?

Upvotes: 0

Views: 475

Answers (1)

Edison Augusthy
Edison Augusthy

Reputation: 1573

This is where environment.ts files comes into picture. In a Angular-Cli project, we get environment folder with two files

  • environment.ts

  • environment.prod.ts

environment.ts

This file exports a constant JSON object environment. If you refer environment object properties in your Angular project, during development mode i.e. ng serve or ng build all values shall be read from this file.

environment.prod.ts

This file exports same JSON object and should have same properties as of environment.ts file. When you build your application for production mode using ng build --prod in that case, all values of environment.ts file shall get overridden by environment.prod.ts files.

Put development HTTP Url inside environment.ts file

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

Put production HTTP URL inside environment.prod.ts file

export const environment = {
  production: true,
  baseUrl: '/backend-folder/public/api'
};

In rest of Angular application, refer environment.baseUrl

import { Injectable } from '@angular/core';
import { environment } from '../environments/environment';
@Injectable({
  providedIn: 'root',
})
export class PathService {
  baseUrl = environment.baseUrl;
  constructor() {}

  DataBasePath() {
   let url = this.baseUrl + '/users/1';
   return this.httpClient.get<JSON>(url);
  }
}

In development mode, run ng serve or ng build command. baseUrl shall read value as if development URL: http://localhost:8000/api For production mode, run ng build --prod command. baseUrl shall read value as if production URL: /backend-folder/public/api

Upvotes: 1

Related Questions