Connecting Angular frontend with Django backend: How to handle API requests?

I’m new to combining Angular with Django and I’m struggling with API requests. I’ve set up a Django backend using rest_framework and an Angular 7 frontend. The issue is that my Angular app is trying to fetch data from its own server (localhost:4200) instead of the Django server (localhost:8000).

Here’s a simplified version of what I’m attempting:

export class DataComponent implements OnInit {
  info: any;
  isLoaded: boolean = false;
  hasIssue: boolean = false;

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.httpClient.get('/api/data').subscribe(
      response => {
        this.info = response;
        console.log(response);
      },
      err => {
        this.isLoaded = true;
        this.hasIssue = true;
        console.log(err);
      }
    );
  }
}

I know I could create a service with a baseUrl variable, but is there a more elegant way to automatically direct all API requests to the backend server? Any guidance or best practices for this kind of setup would be really appreciated!

hey there! have you considered using a proxy configuration in angular? it’s super helpful for redirecting api requests during development. you could set up a proxy.conf.json file to forward requests to your django server. it’s pretty straightforward and keeps your code clean. what do you think about that approach?

yo LucasPixel23, i’ve been there! one trick is to use Angular’s environment files. u can set ur API_URL there and import it in ur components. like this:

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

this.httpClient.get(`${environment.apiUrl}/api/data`)

works like a charm, trust me!