A Guide to Running a Full-Stack Angular Application in a Monorepo

    Jul 9, 20249 min read2629 viewsUpdated:Nov 27, 2024
    A Guide to Running a Full-Stack Angular Application in a Monorepo

    What is Monorepo?

    Monorepo is one type of repository where we can store multiple related projects. And that is very useful for version control, Unlike Polyrepo where we can store different projects in different repositories.

    Key characteristics of Monorepo

    1. Single Repository for Multiple Projects:

      All the code for different projects, services, libraries, etc., is housed within a single repository.

    2. Unified Version Control:

      A single version control system (e.g., Git) manages all projects, ensuring consistency across the codebase.

    3. Shared Dependencies and Tools:

      Common dependencies and tools can be shared across projects without duplication.

    4. Code Sharing and Reuse:

      Facilitates easy code sharing and reuse among different projects.

    5. Single Build and CI Pipeline:

      A unified build and continuous integration (CI) pipeline can be set up for all projects, simplifying the build process and testing.

    Points Advantage
    Code Sharing Easier to manage and update shared libraries/components across all projects.
    Dependency Management Centralized dependency management reduces version conflicts and duplication.
    Refactoring Across Projects Straightforward global refactoring because all projects are in the the same repository.
    Unified Tooling Build systems, linters, formatters, and other tools can be configured once for all projects.
    Collaboration Simplified collaboration and code reviews.

    Points Disadvantage
    Scalability Very large monorepos can become difficult to manage, with longer build times and more complex dependency graphs.
    Tooling Limitations Some version control tools and CI/CD systems may struggle with the scale of a monorepo.
    Access Control Fine-grained access control can be more challenging, as all code is in a single repository.
    Complexity in Managing Changes Coordinating changes across multiple projects can become complex and require more thorough testing.

    Running Full-Stack Applications using Monorepo

    Running a full-stack application in Monorepo involves organizing the frontend framework (Angular) and backend (e.g. Node.js/Express server) codebase in a single repository.

    Here is a step-by-step guide to creating and running full-stack applications using Monorepo

    Step 1: Setting up Monorepo

    • Create a new directory for your project

    • Initialize it with a package manager like 'npm'.

    
    mkdir full-stack-app
    cd full-stack-app
    npm init -y

    Step 2: Creating backend and frontend project

    For creating frontend we are using Angular framework. In the following way, we can create a new angular application.

    ng new angular project --routing --style=scss

    For creating a backend project we are using node.js and express server. In the following way we can create a simple node.js application server.

    mkdir backend
    cd backend
    npm init -y
    npm install express

    Step 3: Integrate with the Backend

    In the backend, we will create a simple server using express.

    For creating that server we will create one index.js file and write our backend code.

    index.js

    const express = require("express");
    const app = express();
    const cors = require("cors");
    const PORT = 8080;
     //Using middleware for getting json(Javascript Object Notation) response. 
    app.use(express.json());
    //cors for preventing malicious website to prevent access sensetive information.
    app.use(cors());
    app.get("/api", (req, res)=>{
    	res.json("Hello this is from backend side");
    });
    app.listen( PORT, ()=>{
    	console.log(`Server is listening on port ${PORT}`);
    }); 

    Step 4: Integrating with angular frontend

    On the Angular front-end side, we have already created the Angular application in Step 2. Now in this step, we will integrate with that application to make backend API calls, get a response from the backend, and print it on the console.

    The best way to make API calls is to generate service in an Angular application.
    So, we will create an API service as api.service.ts

    ng generate service service/api

    When we run the above command in the command line interface it will create api.service.ts in the service folder.

    Code for api.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    @Injectable({
      providedIn: 'root'
    })
    export class ApiService {
      constructor(private _http : HttpClient ) { }
      getData(){
        return this._http.get('http://localhost:8080/api');
      }
    }

    We also need to add HttpClientModule in app.module.ts file which will enable us to use HttpClient service.

    Code for app.module.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

    We are using that service in the Angular component and printing the query result on the console.

    Code for app.compoent.ts

    import { Component } from '@angular/core';
    import {HttpClient} from "@angular/common/http"
    import { tap } from 'rxjs';
    import { ApiService } from './service/api.service';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      title = 'frontend';
      constructor(private _http: HttpClient,private _apiService : ApiService){
        this.getData()
      }
      getData(){
       this._apiService.getData().subscribe({
        next: (data)=>{
          console.log(data);
        },
        error: (error)=>{
          console.error(error.message);
        }
       })
      }
    }

    In this way, our angular frontend source code will be there.

    Running Backend and Frontend application using one command

    For running backend and frontend applications using one command in the command line interface we will do it in the following manner:

    To run the bot application parallelly we need to install it on a package called npm-run-all.

    npm install npm-run-all


    Then, we will go into the global level package.json and in script, we will add a script for running frontend and backend applications.

    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start:frontend": "cd frontend && ng serve",
        "start:backend": "cd backend && node index.js",
        "start": "npm-run-all --parallel start:frontend start:backend"
      },

    After the tutorial, we need to open command line interfaces(CLI) navigate to the root folder, and run the following command:

    npm run start 

    After our application runs successfully, we need to go to the localhost:4200, the default port for angular applications, and we will get the output in the console.

    A MEAN Stack Application

    A MEAN stack application is a full-stack JavaScript-based framework used for developing dynamic web applications. The acronym "MEAN" stands for the four key technologies that make up this stack:

    MongoDB

    A NoSQL database that stores data in JSON-like documents. It is highly flexible and scalable, making it suitable for modern applications that require fast and iterative development.

    Express.js

    A web application framework for Node.js, designed for building web applications and APIs. It provides a robust set of features for web and mobile applications, making it easier to handle routing, middleware, and HTTP requests.

    Angular

    A front-end web application framework developed by Google. It is used for developing single-page applications (SPAs) and follows the MVC (Model-View-Controller) architecture. Angular provides two-way data binding, dependency injection, and modular development, which helps in building dynamic and responsive user interfaces.

    Node.js

    A JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to use JavaScript on the server-side, enabling the creation of scalable and high-performance applications. Node.js handles asynchronous operations efficiently, making it suitable for real-time applications.

    Want to have a strong foundation for your next Angular development project?
    Hire Angular Developer from Angular Minds to get code organization and maintainability for complex applications.

    Key Features of a MEAN Stack Application

    • Single Language Development: JavaScript is used throughout the entire stack, from the client-side to the server-side, and even for database operations. This unification simplifies the development process and allows developers to be more versatile.

    • JSON Everywhere: Data flows seamlessly between layers of the application in JSON format, which JavaScript and MongoDB naturally support.

    • Asynchronous and Non-blocking: With Node.js and its event-driven architecture, MEAN stack applications can handle numerous concurrent connections efficiently without blocking.

    • MVC Architecture: Angular follows the MVC pattern, which helps in separating concerns, making the codebase more manageable and modular.

    • Real-time Data: MEAN stack applications can handle real-time data updates effectively, which is crucial for modern applications such as chat applications, live dashboards, etc.

    Building a MEAN Stack Application

    Set Up MongoDB

    Install MongoDB and configure it to store your application data. Use Mongoose (an ODM library) to define schemas and interact with MongoDB from your Node.js code.

    Develop Server-Side with Node.js and Express.js

    • Create a Node.js application.

    • Use Express.js to set up routes, handle requests, and serve static files.

    • Connect to MongoDB using Mongoose.

    • Implement API endpoints for CRUD operations.

    Create the Front-End with Angular

    • Set up an Angular application using Angular CLI.

    • Develop components, services, and modules to build the user interface.

    • Use Angular’s HttpClient module to communicate with the Express.js backend.

    • Integrate and Deploy:

      • Test the full-stack application to ensure all components work together seamlessly.

      • Use tools like Docker for containerization, making deployment easier and consistent.

      • Deploy the application on cloud platforms such as AWS, Azure, or Heroku.

    Example Use Cases

    • Content Management Systems (CMS): Managing content with real-time updates and user roles.

    • E-commerce Platforms: Handling large amounts of data and user interactions efficiently.

    • Real-Time Applications: Building chat applications, collaborative tools, and live dashboards.

    Conclusion

    So, in this blog, we have learned how to create full-stack applications using frontend as angular and backend as Node.js-like technologies in a single repository that we call angular monorepo, and running full-stack applications using a single command. Here, we got an overall idea of how to set up and run full-stack applications using Monorepo.

    24
    Share
    Hire Expert Angular Developers
    Hire Expert Angular Developers
    With our transparent onboarding process and timezone compatibility, you can hire dedicated Angular Developers in 2-days and jumpstart your project.
    Hire now

    Related articles

    This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.