Using Angular Services to Interact with MongoDB MEAN

๐Ÿ› ️ Using Angular Services to Interact with MongoDB (MEAN Stack)

In the MEAN stack, the front end (Angular) communicates with the back end (Node.js/Express) via HTTP. The back end then interacts with MongoDB to fetch or store data.


๐Ÿ”„ How It All Connects

scss

Copy

Edit

Angular (frontend) --> Express API (backend) --> MongoDB (database)

To keep the Angular frontend clean and maintainable, we use Angular services to handle HTTP requests.


๐Ÿ“ฆ Basic Setup

You’ll need:


Angular CLI


Node.js + npm


Express server


MongoDB (local or hosted)


๐Ÿ“ Folder Structure Overview

bash

Copy

Edit

/client  (Angular)

/server  (Node.js + Express)

/server/models  (Mongoose schemas)

/server/routes  (API routes)

๐Ÿ”ง Step 1: Backend API to Connect to MongoDB

Install dependencies in the /server folder:


bash

Copy

Edit

npm install express mongoose cors body-parser

Create a simple Express API:


js

Copy

Edit

// server/app.js

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');


const app = express();

const port = 3000;


app.use(cors());

app.use(express.json());


mongoose.connect('mongodb://localhost:27017/your-db', {

  useNewUrlParser: true,

  useUnifiedTopology: true

});


const Item = mongoose.model('Item', { name: String });


app.get('/api/items', async (req, res) => {

  const items = await Item.find();

  res.json(items);

});


app.post('/api/items', async (req, res) => {

  const newItem = new Item(req.body);

  await newItem.save();

  res.status(201).send(newItem);

});


app.listen(port, () => {

  console.log(`Server is running on http://localhost:${port}`);

});

๐Ÿ’ป Step 2: Angular Service to Call the API

Generate a service:


bash

Copy

Edit

ng generate service services/item

Edit item.service.ts:


ts

Copy

Edit

// src/app/services/item.service.ts

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

import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';


@Injectable({

  providedIn: 'root',

})

export class ItemService {

  private apiUrl = 'http://localhost:3000/api/items';


  constructor(private http: HttpClient) {}


  getItems(): Observable<any> {

    return this.http.get(this.apiUrl);

  }


  addItem(item: any): Observable<any> {

    return this.http.post(this.apiUrl, item);

  }

}

๐Ÿงฑ Step 3: Using the Service in a Component

In your Angular component:


ts

Copy

Edit

// src/app/app.component.ts

import { Component, OnInit } from '@angular/core';

import { ItemService } from './services/item.service';


@Component({

  selector: 'app-root',

  template: `

    <div *ngFor="let item of items">{{ item.name }}</div>

    <button (click)="addItem()">Add Item</button>

  `,

})

export class AppComponent implements OnInit {

  items: any[] = [];


  constructor(private itemService: ItemService) {}


  ngOnInit(): void {

    this.itemService.getItems().subscribe((data) => {

      this.items = data;

    });

  }


  addItem() {

    const newItem = { name: 'New Item' };

    this.itemService.addItem(newItem).subscribe((item) => {

      this.items.push(item);

    });

  }

}

✅ Summary

Angular uses a service to send HTTP requests to the backend.


Node.js/Express handles the routes and communicates with MongoDB.


Mongoose is used to interact with MongoDB using schemas/models.

Learn MEAN Stack Course

Read More

Form Validation in Angular with Express API Integration MEAN

CRUD Operations Using MEAN Stack

Visit Our Quality Thought Training in Hyderabad

Get Directions 

Comments

Popular posts from this blog

Entry-Level Cybersecurity Jobs You Can Apply For Today

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners