Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make dynamic API calls in Angular project

I’m using the following Typescript function to get access to API data:

export class BomService {

  constructor(private http: HttpClient) { }

  GetAllBomList(): Observable<IBom[]> {
    return this.http.get<IBom[]>('http:192.168.10.1:5000/api/bom/getallboms');
  }
}

When I use my own computer I can load data completely but when I’m trying to get access through Internet, the UI is loaded but the data cannot be fetched. The reason is Http address. Both the API and the UI are hosted in the same server using IIS. How can I solve this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Angular < 15 has an environments folder. Angular 15+ you need first call ng g environments inside your project. Then you see this folders/files (names can be different of the files)

enter image description here

The files looks like this:

environment.development

export const environment = {
  serverPath: 'http://localhost:3000',
};

environment (production)

export const environment = {
  serverPath: 'http://123.123.123.123:3000', // Server path
};

The rest of the magic do Angular for you. So in your service/component or what you want you need to import the file like this:

Service

import { environment } from 'src/environments/environment';

...

  GetAllBomList(): Observable<IBom[]> {
    return this.http.get<IBom[]>(environment.serverPath + '/api/bom/getallboms');
  }

Read all about environments here. But in short: In the angular.json file you will find the environments files. One for dev and one for production. If you run ng build Angular will replace the dev file with the production file. You need to do nothing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading