Help needed to link my Angular app with my Express API. I’ve got a working API that handles JSON data in Postman, but I’m struggling to display this on my Angular frontend.
My goal is to create a contact list app. It should have:
- A form with fields for id, first name, last name, and email
- A list showing existing contacts from the API
- Ability to add new contacts via the form
- Option to click on a contact for more details
Here’s a simplified version of my backend code:
const express = require('express');
const app = express();
const contacts = [];
app.use(express.json());
app.get('/contacts', (req, res) => {
res.json(contacts);
});
app.post('/contacts', (req, res) => {
const newContact = req.body;
contacts.push(newContact);
res.status(201).json(newContact);
});
app.listen(3000, () => console.log('Server running on port 3000'));
Any tips on how to connect this with my Angular frontend would be greatly appreciated. I’m new to full-stack development, so please bear with me!
To connect your Angular frontend with your Express backend, you’ll need to set up an HTTP client in Angular, typically using the HttpClient module. First, import HttpClientModule in your app.module.ts file. Then, create a service to handle API requests. In this service, inject HttpClient and use its methods (get, post, etc.) to communicate with your Express endpoints.
For your contact list app, create components for the form and list. In the form component, use Angular’s reactive forms to handle user input. When submitting, call your service’s method to send a POST request to ‘/contacts’. For the list, use ngOnInit to fetch contacts with a GET request to ‘/contacts’. Display the data using *ngFor directive.
Remember to handle CORS on your Express server by adding appropriate headers or using a package like cors. This setup should allow your Angular app to seamlessly interact with your Express API.
hey there! have u tried using HttpClient in angular? it’s super helpful for api stuff. maybe create a contact service? ooh, and for that contact list, *ngFor is ur best friend! btw, what kinda validation are u thinking for the form? curious minds wanna know! 
hey max, i’ve been there! for ur angular app, create a service using HttpClient. import it in component, inject in constructor. use get() for fetching contacts, post() for adding. in html, use *ngFor to display list. don’t forget to enable CORS on express side. good luck!