Complete fullstack application with ionic-angular and nodejs tutorial from basic to advance using coding examples

 Building a full-stack application with Iionic-Angular as the frontend and Node.js as the backend involves several steps. The frontend will be responsible for rendering the UI and interacting with the user, while the backend will handle data management and provide APIs for the frontend.

This tutorial will walk you through creating a complete full-stack application, starting from the basics to more advanced features. The tutorial includes examples of both the Ionic-Angular frontend and Node.js backend.


Overview of the Full-Stack Application

We will build a simple Task Management Application where users can:

  • Create, view, update, and delete tasks.
  • The frontend will be built with Ionic-Angular, and the backend will be built with Node.js (Express) and MongoDB for data storage.

1. Setting up the Backend (Node.js + MongoDB)

1.1. Initialize Node.js Backend

Start by setting up the Node.js backend using Express.

  1. Create a new directory for the backend:

    bash
    mkdir task-manager-backend cd task-manager-backend
  2. Initialize a new Node.js project:

    bash
    npm init -y
  3. Install dependencies:

    bash
    npm install express mongoose cors dotenv
    • express: The web framework for Node.js.
    • mongoose: MongoDB object modeling for Node.js.
    • cors: Middleware for handling Cross-Origin Resource Sharing.
    • dotenv: To load environment variables.
  4. Create the server file (server.js):

    javascript
    const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const dotenv = require('dotenv'); dotenv.config(); const app = express(); app.use(cors()); app.use(express.json()); const PORT = process.env.PORT || 5000; // MongoDB Connection mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.log(err)); // Task Model const taskSchema = new mongoose.Schema({ title: { type: String, required: true }, description: { type: String, required: true }, completed: { type: Boolean, default: false }, }); const Task = mongoose.model('Task', taskSchema); // Routes app.get('/tasks', async (req, res) => { const tasks = await Task.find(); res.json(tasks); }); app.post('/tasks', async (req, res) => { const newTask = new Task(req.body); await newTask.save(); res.status(201).json(newTask); }); app.put('/tasks/:id', async (req, res) => { const updatedTask = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.json(updatedTask); }); app.delete('/tasks/:id', async (req, res) => { await Task.findByIdAndDelete(req.params.id); res.status(204).send(); }); // Start Server app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
  5. Create a .env file for environment variables:

    bash
    MONGO_URI=mongodb://localhost:27017/task-manager

1.2. Start the Backend Server

  1. Run the server:
    bash
    node server.js
    The backend server should now be running on http://localhost:5000.

2. Setting up the Frontend (Ionic-Angular)

2.1. Create an Ionic-Angular Application

  1. Create a new Ionic project:

    bash
    ionic start task-manager-app blank --type=angular cd task-manager-app
  2. Install the HTTP client to interact with the backend:

    bash
    npm install @angular/common/http

2.2. Create a Service for API Communication

  1. Generate a service for API communication:

    bash
    ionic generate service services/task
  2. Modify task.service.ts to handle HTTP requests:

    typescript
    import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; interface Task { _id?: string; title: string; description: string; completed: boolean; } @Injectable({ providedIn: 'root' }) export class TaskService { private apiUrl = 'http://localhost:5000/tasks'; constructor(private http: HttpClient) {} getTasks(): Observable<Task[]> { return this.http.get<Task[]>(this.apiUrl); } createTask(task: Task): Observable<Task> { return this.http.post<Task>(this.apiUrl, task); } updateTask(taskId: string, task: Task): Observable<Task> { return this.http.put<Task>(`${this.apiUrl}/${taskId}`, task); } deleteTask(taskId: string): Observable<void> { return this.http.delete<void>(`${this.apiUrl}/${taskId}`); } }

2.3. Create the Task Page for Displaying Tasks

  1. Modify home.page.ts to use the TaskService to fetch and display tasks:

    typescript
    import { Component, OnInit } from '@angular/core'; import { TaskService } from '../services/task.service'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit { tasks = []; constructor(private taskService: TaskService) {} ngOnInit() { this.loadTasks(); } loadTasks() { this.taskService.getTasks().subscribe(data => { this.tasks = data; }); } addTask() { const newTask = { title: 'New Task', description: 'Task description', completed: false }; this.taskService.createTask(newTask).subscribe(task => { this.tasks.push(task); }); } deleteTask(taskId: string) { this.taskService.deleteTask(taskId).subscribe(() => { this.tasks = this.tasks.filter(task => task._id !== taskId); }); } }
  2. Modify home.page.html to display tasks and add buttons for interaction:

    html
    <ion-header> <ion-toolbar> <ion-title>Task Manager</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-button (click)="addTask()">Add Task</ion-button> <ion-list> <ion-item *ngFor="let task of tasks"> <ion-label> <h2>{{ task.title }}</h2> <p>{{ task.description }}</p> </ion-label> <ion-button color="danger" (click)="deleteTask(task._id)">Delete</ion-button> </ion-item> </ion-list> </ion-content>

3. Testing the Full-Stack Application

  1. Ensure MongoDB is running locally.
  2. Start the backend server using node server.js.
  3. Run the Ionic frontend:
    bash
    ionic serve
    This will open the app in the browser, and you should be able to add, view, and delete tasks.

4. Advanced Features (Optional)

4.1. User Authentication (JWT Authentication)

  • Backend: Implement JWT-based authentication for user login and registration.
  • Frontend: Use Angular's HTTP interceptor to send the JWT token with each API request.

4.2. Task Filtering and Sorting

  • Implement task filtering and sorting features based on status (completed/incomplete) or other criteria like date created.

In home.page.ts:

typescript
filterTasks(completed: boolean) { this.tasks = this.tasks.filter(task => task.completed === completed); }

In home.page.html:

html
<ion-button (click)="filterTasks(true)">Show Completed</ion-button> <ion-button (click)="filterTasks(false)">Show Incomplete</ion-button>

4.3. Deployment to Production

  1. Backend:

    • Deploy the backend to a cloud service like Heroku, DigitalOcean, or AWS.
    • Set up a production MongoDB instance (e.g., MongoDB Atlas).
  2. Frontend:

    • Build the Ionic app for production:
      bash
      ionic build --prod
    • Deploy the built app to a static hosting service like Firebase Hosting, Netlify, or Vercel.

Conclusion

This tutorial provided the basics of creating a full-stack Ionic-Angular and Node.js application. You learned how to:

  1. Set up a Node.js backend with MongoDB to manage tasks.
  2. Create an Ionic-Angular frontend to interact with the backend.
  3. Perform CRUD operations to manage tasks in the app.

By adding more features such as user authentication, task filtering, and deployment, you can further extend the application and prepare it for production use.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics