Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE :: Angular Subscription Management: Using RxJS to Fix Memory Leaks

clock July 21, 2025 08:26 by author Peter

Angular uses RxJS Observables quite extensively for asynchronous data anything from HTTP requests, form value changes, events, route parameters, and many more. Most of the time, you would subscribe to them, but not unsubscribing properly may cause memory leaks and unexpected behavior, especially in large or long-running apps. In this article, we share how we faced a real-life issue related to missed unsubscriptions, how we identified the leak, and how we applied best practices, such as the takeUntil operator and a reusable base class.

Real Scenario
In various dashboard applications, several components had the possibility of listening to data streams coming from the API, user interactions, and changes in route parameters. Such components use subscription on observables through the RxJS subscribe() method inside the Angular lifecycle hooks of ngOnInit().

Example
ngOnInit(): void {
  this.route.params.subscribe(params => {
    this.loadData(params['id']);
  });

  this.userService.getUser().subscribe(user => {
    this.user = user;
  });
}


After navigating between routes multiple times, we noticed the following issues.

  • Console logs appeared multiple times for the same action.
  • Network requests were duplicated.
  • The browser’s memory usage slowly increased over time.

Root Cause

  • Upon inspection using Chrome DevTools memory tab and Angular DevTools, we found that components were not being garbage collected. This was due to active subscriptions holding references to destroyed components.
  • Solution: Using the takeUntil Pattern with Subject.

To fix this, we implemented the takeUntil pattern with a private Subject.

Step 1. Declare an Unsubscribe Subject.
private destroy$ = new Subject<void>();

Step 2. Use takeUntil(this.destroy$) in Every Subscription.
ngOnInit(): void {
  this.route.params
    .pipe(takeUntil(this.destroy$))
    .subscribe(params => this.loadData(params['id']));

  this.userService.getUser()
    .pipe(takeUntil(this.destroy$))
    .subscribe(user => this.user = user);
}


Step 3. Emit and complete the Subject in ngOnDestroy().
ngOnDestroy(): void {
  this.destroy$.next();
  this.destroy$.complete();
}

This pattern ensures that all subscriptions automatically unsubscribe when the component is destroyed.

Improvement: Create a Base Component Class

To avoid repeating the same code in every component, we created a base class.
export abstract class BaseComponent implements OnDestroy {
  protected destroy$ = new Subject<void>();

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}


Now, in any component.
export class MyComponent extends BaseComponent implements OnInit {

  ngOnInit(): void {
    this.dataService.getData()
      .pipe(takeUntil(this.destroy$))
      .subscribe(data => this.data = data);
  }

}


Alternative Approach: AsyncPipe for Simpler Cases
In cases where we can bind observables directly in the template, we prefer using Angular’s AsyncPipe, which handles subscription and unsubscription automatically.

Instead of,
this.dataService.getData().subscribe(data => {
  this.data = data;
});


Use in the template.
data$ = this.dataService.getData();

<div *ngIf="data$ | async as data">
  {{ data.name }}
</div>


Conclusion
Failing to unsubscribe from observables in Angular can lead to performance issues, duplicate API calls, and memory leaks. Using takeUntil with a Subject is a reliable and scalable solution, especially when combined with a base component class. For simpler use cases, Angular's AsyncPipe provides a clean and safe way to handle subscriptions in templates. Adhering to these practices keeps your Angular applications running smoothly, easy to maintain, and protected from those memory leaks that can improve performance. You will maintain both efficiency and code clarity as a result.



AngularJS Hosting Europe - HostForLIFE :: Using Angular Route Guards to Secure Routes

clock July 16, 2025 10:07 by author Peter

Depending on whether a user is logged in or has particular permissions, we frequently need to limit access to particular routes in Angular apps. Angular offers Route Guards, like CanActivate, to protect certain routes. In one of our projects, we had to prevent users from accessing the dashboard unless they were authenticated. We created an AuthGuard with CanActivate and added logic to check if the user token was locally stored. Everything was running fine until we released the app.


 Some users claimed that they were repeatedly taken to the login screen even if they were already logged in.

Reasons for the Problem
We found that timing was the cause of the problem. The guard attempted to verify the token before the validation was finished, even though the app had already called the API to validate the token at startup. It is therefore believed that the user was not authenticated.

How did we fix it?

Our AuthGuard logic has been modified to wait for validation to complete before granting or denying access. We used a shared AuthService with an isAuthenticated$ observable rather than just checking local storage.

Here’s how we adjusted the AuthGuard.
canActivate(): Observable<boolean> {
  return this.authService.isAuthenticated$.pipe(
    take(1),
    map(isAuth => {
      if (!isAuth) {
        this.router.navigate(['/login']);
        return false;
      }
      return true;
    })
  );
}


And in the AuthService, we updated the token status using a BehaviorSubject once the API response came back.
private authStatus = new BehaviorSubject<boolean>(false);

isAuthenticated$ = this.authStatus.asObservable();

validateToken() {
  // Call backend to validate token
  this.http.get('/api/validate-token').subscribe(
    () => this.authStatus.next(true),
    () => this.authStatus.next(false)
  );
}

We called validateToken() once in AppComponent during app initialization.

Conclusion
Route guards are essential for secure routing in Angular apps. But they must be carefully integrated with authentication logic, especially when token validation involves an async call. Using an observable approach helps in handling real-time state and avoiding premature navigation decisions.



AngularJS Hosting Europe - HostForLIFE :: Using Angular Route Guards to Secure Routes

clock July 14, 2025 08:33 by author Peter

Depending on whether a user is logged in or has particular permissions, we frequently need to limit access to particular routes in Angular apps. Angular offers Route Guards, like CanActivate, to protect certain routes. In one of our projects, we had to prevent users from accessing the dashboard unless they were authenticated. We created an AuthGuard with CanActivate and added logic to check if the user token was locally stored. Everything was running fine until we released the app.


Some users claimed that they were repeatedly taken to the login screen even if they were already logged in.

Reasons for the Problem
We found that timing was the cause of the problem. The guard attempted to verify the token before the validation was finished, even though the app had already called the API to validate the token at startup. It is therefore believed that the user was not authenticated.

How did we fix it?
Our AuthGuard logic has been modified to wait for validation to complete before granting or denying access. We used a shared AuthService with an isAuthenticated$ observable rather than just checking local storage.

Here’s how we adjusted the AuthGuard.

canActivate(): Observable<boolean> {
  return this.authService.isAuthenticated$.pipe(
    take(1),
    map(isAuth => {
      if (!isAuth) {
        this.router.navigate(['/login']);
        return false;
      }
      return true;
    })
  );
}


And in the AuthService, we updated the token status using a BehaviorSubject once the API response came back.
private authStatus = new BehaviorSubject<boolean>(false);

isAuthenticated$ = this.authStatus.asObservable();

validateToken() {
  // Call backend to validate token
  this.http.get('/api/validate-token').subscribe(
    () => this.authStatus.next(true),
    () => this.authStatus.next(false)
  );
}


We called validateToken() once in AppComponent during app initialization.

Conclusion
Route guards are essential for secure routing in Angular apps. But they must be carefully integrated with authentication logic, especially when token validation involves an async call. Using an observable approach helps in handling real-time state and avoiding premature navigation decisions.



Node.js Hosting - HostForLIFE :: Building a Simple REST API in Node.js (GET, POST, PUT, DELETE)

clock July 10, 2025 08:19 by author Peter

Node.js is a robust framework for JavaScript server-side application development. GET, POST, PUT, and DELETE are the fundamental methods of every CRUD (Create, Read, Update, Delete) action, and we'll show you how to create a basic REST API that supports them in this article.

To keep things clear and easy, we'll use the well-liked Express framework.

First, start a Node.js project
To begin, make a new folder for your project and set up npm for it.

mkdir nodejs-api-demo
cd nodejs-api-demo
npm init -y


Then, install Express,
npm install express

Step 2. Create the API Server
Create a file named server.js and write the following code.
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json()); // Middleware to parse JSON
let items = []; // Sample in-memory data store
// GET all items
app.get('/api/items', (req, res) => {
    res.json(items);
});
// POST a new item
app.post('/api/items', (req, res) => {
    const newItem = {
        id: Date.now(),
        name: req.body.name
    };
    items.push(newItem);
    res.status(201).json(newItem);
});

// PUT (update) an item by ID
app.put('/api/items/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const index = items.findIndex(item => item.id === id);

    if (index !== -1) {
        items[index].name = req.body.name;
        res.json(items[index]);
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// DELETE an item by ID
app.delete('/api/items/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const initialLength = items.length;
    items = items.filter(item => item.id !== id);

    if (items.length < initialLength) {
        res.json({ message: 'Item deleted' });
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// Hello World Endpoint
app.get('/', (req, res) => {
    res.send('Hello, World!');
});
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});


Step 3. Run Your API
Start your server using.

node server.js
Open your browser and go to:http://localhost:3000/ You should see "Hello, World!"

Use tools like Postman, Insomnia, or curl to test other endpoints:

  • GET http://localhost:3000/api/items
  • POST http://localhost:3000/api/items with JSON body: { "name": "Apple" }
  • PUT http://localhost:3000/api/items/123456789 with JSON: { "name": "Banana" }
  • DELETE http://localhost:3000/api/items/123456789

Summary
In this tutorial, you learned how to.

  • Initialize a Node.js project
  • Install and use Express.js
  • This setup is great for learning. For production, consider connecting to a real database, such as MongoDB, PostgreSQL, or MySQL.
  • Handle JSON data and HTTP methods (GET, POST, PUT, DELETE)
  • Build a basic in-memory CRUD API


Node.js Hosting - HostForLIFE :: Knowing Node.js's Event Loop, Callbacks, and Promises

clock July 3, 2025 08:00 by author Peter

The ability of Node.js to manage asynchronous processes is a major factor in its strength for creating quick, scalable network applications. You've probably heard of concepts like promises, callbacks, and event loops if you've ever dealt with Node.js.

In this post, we'll simplify these, go over actual code samples, and discuss how they all work together in the context of asynchronous programming.

Asynchronous programming: what is it?
JavaScript (as well as Node.js) only handles one instruction at a time since it is single-threaded. Unless we handle it asynchronously, if one operation (such as reading a file or sending a network request) takes a long time, it may prevent all other tasks from operating. Node.js can manage operations like file I/O, database queries, and API calls thanks to asynchronous programming, which keeps the application from stopping altogether.

The Event Loop: Node's Brain
The event loop is a mechanism in Node.js that allows it to perform non-blocking I/O operations. It listens for events and runs tasks from different queues (like timers or promise resolutions).

How does it work?

  • Executes synchronous code first.
  • Handles microtasks (like Promise.then()).
  • Then processes macrotasks (like setTimeout).
  • Repeats the cycle.

Example
console.log('Start');

setTimeout(() => {
  console.log('Timeout callback');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise callback');
});
console.log('End');


Output
Start
End
Promise callback
Timeout callback


Why?

  • Promise.then() is a microtask, executed right after the synchronous code.
  • setTimeout() is a macrotask, executed after microtasks.

Callbacks: The Classic Asynchronous Tool
What is a Callback?

A callback is a function passed as an argument to another function. It’s executed when the first function completes - often asynchronously.
const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  console.log(data);
});

Callback Hell
As you nest callbacks deeper, code can become hard to manage.
doTask1((res1) => {
  doTask2(res1, (res2) => {
    doTask3(res2, (res3) => {
      console.log(res3);
    });
  });
});


This “pyramid of doom” led to the evolution of promises.
Promises: A Modern Alternative

What is a Promise?
A promise is an object representing the eventual completion or failure of an asynchronous operation.
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});
myPromise
  .then((value) => console.log(value))
  .catch((err) => console.error(err));

Promise States

  • Pending: Initial state.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed.

Promises in Action
function asyncTask() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('Task Done'), 2000);
  });
}
asyncTask().then(console.log); // Outputs "Task Done" after 2 seconds


Async/Await: Cleaner Syntax with Promises

Introduced in ES2017, async/await allows you to write asynchronous code like it’s synchronous.
async function fetchData() {
  try {
    const data = await asyncTask();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
fetchData();

This is still based on promises, but it's easier to read and write.

Event Loop + Promises + Callbacks: Putting It Together

console.log('Start');

setTimeout(() => {
  console.log('setTimeout');
}, 0);

Promise.resolve().then(() => {
  console.log('Promise');
});

process.nextTick(() => {
  console.log('nextTick');
});
console.log('End');

Output
Start
End
nextTick
Promise
setTimeout

Execution order

  • Synchronous: Start, End
  • process.nextTick() (before promises)
  • Promises
  • Timers like setTimeout

Summary Table

Concept Purpose Queue
Event Loop Runs and manages all tasks          —
Callback Function called after async operation Callback queue
Promise Handles future values (success/failure) Microtask queue
setTimeout Delay execution of a task Macrotask queue
process.nextTick Runs after the current phase, before promises Microtask queue (special)

Conclusion

Node.js manages concurrency via non-blocking, asynchronous APIs and a clever event loop rather than threads. The event loop, promises, and callbacks are all crucial for creating Node.js applications with great performance. You will soon be able to create async code with confidence if you start small, try out samples, and gradually develop your mental model.



Node.js Hosting Europe - HostForLIFE :: Key Features of Node.js: A Clear Explanation

clock July 1, 2025 07:24 by author Peter

An open-source, cross-platform runtime environment called Node.js enables server-side JavaScript execution. It is incredibly fast because it is based on Chrome's V8 engine. Node.js's non-blocking, event-driven architecture is one of its strongest features; it makes it easier to create high-performance applications. Because we can use the same language-JavaScript-for both front-end and back-end development, many Indian developers.

Why Node.js is So Popular: 7 Key Features Explained?
Speed, scalability, and performance are essential for creating contemporary web applications in the fast-paced digital world of today. Node.js excels in this situation. Node.js has grown to be one of the most popular platforms since its launch, used by both developers and businesses, ranging from startups to internet behemoths like Netflix, PayPal, and LinkedIn.

1. Single-Threaded but Super Efficient
Node.js operates on a single-threaded event loop, in contrast to conventional server models that employ many threads. This implies that thousands of requests can be handled concurrently without requiring the creation of a new thread for each one. I/O-intensive applications like as file upload systems, chat apps, and streaming services are best suited for this.

2. Asynchronous and Non-Blocking
In Node.js, operations like reading files or querying a database do not block the main thread. Instead, they run in the background and notify when the task is complete. This non-blocking nature allows other tasks to continue running smoothly, perfect for high-performance apps.

3. Event-Driven Architecture
Everything in Node.js revolves around events. Instead of waiting for a process to complete, Node.js listens for events and responds accordingly. This event-driven nature improves performance and helps build scalable applications.

4. Powered by Google’s V8 Engine
Node.js uses Google’s powerful V8 JavaScript engine, the same engine used in Chrome. It compiles JavaScript directly into machine code, making it extremely fast and efficient.

5. Cross-Platform Support

Whether you are using Windows, macOS, or Linux, Node.js works seamlessly across platforms. This makes development flexible and accessible to a wider range of developers.

6. NPM – Node Package Manager
With Node.js, you get access to NPM, the world’s largest software registry. It contains thousands of free packages and libraries that you can easily install and use in your projects, saving a lot of development time.

7. Built for Real-Time Applications

One of the biggest strengths of Node.js is its real-time capabilities. Whether you’re building a messaging app, online multiplayer game, or live tracking system, Node.js offers the perfect foundation for real-time communication.

Conclusion
Node.js is a comprehensive ecosystem that enables developers to create quick, scalable, and contemporary apps. It is not just another server-side technology. It is perfect for today's digital demands because of its single-threaded paradigm, asynchronous nature, and real-time characteristics. If you're an Indian developer who wants to improve your backend skills, learning Node.js can lead to a lot of options.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in