Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: Error handling in Angular

clock January 20, 2025 06:34 by author Peter

In order to guarantee a seamless user experience and facilitate debugging, Angular error management entails recording and controlling errors. Angular comes with a number of built-in tools and methods for methodically managing faults.


1. Managing Errors in HTTP

The HttpClient and the catchError operator from RxJS can be used to manage errors in HTTP requests.

For instance
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private apiUrl = 'https://api.example.com/data';

  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get(this.apiUrl).pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // Client-side error
      console.error('Client-side error:', error.error.message);
    } else {
      // Server-side error
      console.error(`Server-side error: ${error.status} - ${error.message}`);
    }
    return throwError(() => new Error('Something went wrong; please try again later.'));
  }
}


catchError: Intercepts errors and allows custom handling.
throwError: Re-throws the error after handling it for further processing.

2. Global Error Handling
Angular provides a way to handle application-wide errors using the ErrorHandler service.

Custom Global Error Handler.
Create a custom error handler.
import { ErrorHandler, Injectable, NgZone } from '@angular/core';

  @Injectable()
  export class GlobalErrorHandler implements ErrorHandler {
    constructor(private ngZone: NgZone) {}

    handleError(error: any): void {
      // Log the error to the console or a logging service
      console.error('Global Error:', error);

      // Notify the user (e.g., using a toast or modal)
      this.ngZone.run(() => {
        alert('An unexpected error occurred.');
      });
    }
  }
   

Register the error handler in AppModule.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { GlobalErrorHandler } from './global-error-handler';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }],
  bootstrap: [AppComponent]
})
export class AppModule {}

The service will be used throughout the entire application to catch logs.

3. Error Interceptors
Use an HTTP interceptor to handle errors globally for all HTTP requests.

Example

Create an HTTP interceptor.
  import { Injectable } from '@angular/core';
  import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
  import { catchError, throwError } from 'rxjs';

  @Injectable()
  export class ErrorInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
      return next.handle(req).pipe(
        catchError((error: HttpErrorResponse) => {
          // Handle different error types
          if (error.status === 404) {
            console.error('Not Found:', error.message);
          } else if (error.status === 500) {
            console.error('Server Error:', error.message);
          }

          // Optionally, rethrow the error
          return throwError(() => new Error('An error occurred. Please try again later.'));
        })
      );
    }
  }
   

Register the interceptor in AppModule.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ErrorInterceptor } from './error-interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorInterceptor,
      multi: true
    }
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule {}

4. Using Angular Guards for Route Error Handling
Angular guards can protect routes and handle access-related errors.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    const isAuthenticated = false; // Replace with actual authentication logic
    if (!isAuthenticated) {
      alert('You are not authorized to access this page.');
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}


5. Error Display in the UI
Display user-friendly error messages in the UI using Angular components.

Example
Create an error message component.
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-error-message',
  template: `
    <div *ngIf="errorMessage" class="error">
      {{ errorMessage }}
    </div>
  `,
  styles: [
    `
      .error {
        color: red;
      }
    `,
  ],
})
export class ErrorMessageComponent {
  @Input() errorMessage: string | null = null;
}



Use the component.
<app-error-message [errorMessage]="error"></app-error-message>

6. RxJS Error Handling Strategies
    Retry Failed Requests.
    import { retry } from 'rxjs';

    this.http.get(this.apiUrl).pipe(
      retry(3), // Retry up to 3 times
      catchError(this.handleError)
    );

Fallback Data.
this.http.get(this.apiUrl).pipe(
  catchError(() => of([])) // Return fallback data on error
);


7. Logging Errors
Use external services like Sentry, LogRocket, or custom logging services to log errors.

Example
@Injectable({
  providedIn: 'root'
})
export class LoggingService {
  logError(message: string, stack: string) {
    // Send error logs to an external server
    console.log('Logging error:', message);
  }
}




Node.js Hosting Europe - HostForLIFE.eu :: How To Creating a Live Chat App Using Socket.IO and Node.js?

clock January 16, 2025 07:48 by author Peter

A fundamental element of modern web development is the usage of live chat software to enable real-time user contact. Using technologies like Socket.IO and Node.js greatly simplifies the process. Socket.IO is a JavaScript library that allows bidirectional, real-time communication between web clients and servers, resulting in stable connections across all browsers. Node.js, a stable runtime environment that uses an event-driven, non-blocking I/O model, makes it simple to create scalable network applications.

Steps for Creating a Project]
Step 1. Setting Up the Project
Use my previous article for setting up Node.js, "How to upload file in Node.js" In this article, we mentioned important commands for uploading files in Node.js.

Step 2. Setting Up the Server
Create the Server File. Create a file named index.js
const express = require('express');
const app = express();
const { Server } = require('socket.io');
const http = require('http');
const server = http.createServer(app);
const io = new Server(server);
const port = 4000;
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
    socket.on('send name', (username) => {
        io.emit('send name', username);
    });
    socket.on('send message', (chat) => {
        io.emit('send message', chat);
    });
});
server.listen(port, () => {
    console.log(`Server is listening at the port: ${port}`);
});

Step 3. Creating the Frontend

Create the HTML File. Create a file named index.html
<!DOCTYPE html>
<html>
<head>
    <title>Chat app using Socket IO and Node JS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        h1 {
            color: #273c75;
        }

        .msg-box {
            display: flex;
            flex-direction: column;
            background: darkgray;
            padding: 20px;
        }
    </style>
</head>
<body>
    <h1 class="font-bold text-3xl text-center mt-5">
        C# Corner Chat App using Socket IO and Node JS
    </h1>
    <div>
    </div>
    <form class="flex flex-col justify-center items-center mt-5" id="form">
        <div class="msg-box">
            <input class="border border-gray-400 rounded-md mt-5 p-1" type="text" placeholder="Name" id="myname"
                autocomplete="off">
            <input class="border border-gray-400 rounded-md mt-5 p-1" type="text" placeholder="Message" id="message"
                autocomplete="off">
            <button class="bg-blue-500 rounded-md p-2 text-white mt-5">
                Send
            </button>
        </div>
    </form>
    <div class="flex flex-col justify-center items-center mt-5" id="messageArea">
    </div>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
    let socket = io();
    let form = document.getElementById('form');
    let myname = document.getElementById('myname');
    let message = document.getElementById('message');
    let messageArea = document.getElementById("messageArea");
    form.addEventListener("submit", (e) => {
        e.preventDefault();
        if (message.value) {
            socket.emit('send name', myname.value);
            socket.emit('send message', message.value);
            message.value = "";
        }
    });
    socket.on("send name", (username) => {
        let name = document.createElement("p");
        name.style.backgroundColor = "#a59494";
        name.style.textAlign = "center";
        name.style.color = "white";
        name.textContent = username + ":";
        messageArea.appendChild(name);
    });
    socket.on("send message", (chat) => {
        let chatContent = document.createElement("p");
        chatContent.textContent = chat;
        messageArea.appendChild(chatContent);
    });
</script>
</html>

Step 4. Running the Application
Run the command in CMD.
node index.js

In the output, you can open the chat application in two different browsers or different tabs. When you start typing and send a message, it reflects on both screens in real-time.

Conclusion

You have now successfully used Node.js and Socket.IO to develop a basic live chat application. This application facilitates real-time communication between users by rapidly reflecting messages across several linked clients. To make your app even better, think about including features like private messaging, user authentication, and database storage for conversation history. Using CSS frameworks or original designs to enhance the user interface can improve the user experience. Use Vercel or Heroku to launch your application for increased accessibility. Continue researching and experimenting to create a robust and feature-rich chat experience. Enjoy yourself while coding!



AngularJS Hosting Europe - HostForLIFE.eu :: Using Pipes to Create Clear and Effective Angular Applications

clock January 8, 2025 06:45 by author Peter

The use of "pipes" is one of Angular's most potent tools for formatting and changing data inside templates. Developers can apply transformations like formatting dates, changing text cases, or even filtering data in an efficient and reusable way by using pipes, which offer a declarative mechanism to handle data before it is shown to the user.

Writing clean, manageable, and modular code for Angular applications requires an understanding of pipes. The main distinctions between pipes and functions will be discussed in this post, along with how to use built-in pipes and make your own custom pipes to increase Angular's functionality. You will have a firm grasp on how to integrate pipes into your Angular projects to improve user experience and expedite data presentation by the end of this tutorial.

What is an Angular Pipe?
In Angular, a pipe is a way to transform data before it is displayed in the user interface. Pipes can be used in templates to modify or format data without having to alter the original data.

Pipes are an Angular concept, not a TypeScript (TS) feature. They are a core part of Angular’s template syntax and are used to transform data in the view (template) layer of Angular applications.

Key Points about Pipes in Angular

  • Angular-Specific: Pipes are a built-in feature of the Angular framework designed to be used in Angular templates. They are not a native feature of JavaScript or TypeScript.
  • Purpose: Their primary function is to transform data in the template before it is displayed to the user. This transformation can include formatting dates, numbers, currencies, filtering arrays, or performing more complex data transformations.

Declarative Transformation: Pipes enable declarative transformation of data within the template, meaning that the logic for transforming data is cleanly abstracted away from the component’s TypeScript code.

You may be wondering why we should use Pipes when we can use functions.

Criteria Pipe Function
Purpose Data transformation in the template Business logic and calculations
Use case Formatting, filtering, sorting, etc. Complex or multi-step calculations
Performance Pure pipes are efficient for transforming data only when needed Functions can be less performant when used in templates (requires manual calls)
Reusability Highly reusable across templates Functions are reusable within the component or service
Asynchronous Handling Handles observables and promises with AsyncPipe Requires manual subscription logic or use of 'async' in templates
Complexity Best for simple, declarative transformations Best for complex or dynamic logic
When to use When transforming data for display in the template When performing business logic or side effects that don't belong in the template

Types of Pipes
There are two types of Pipes.
Pure Pipe (Default): A pure pipe will only re-run when its input value changes.
    @Pipe({

      name: 'pureExample',

      pure: true // This is the default value, so you can omit this

    })

    export class PureExamplePipe implements PipeTransform {

      transform(value: any): any {

        console.log('Pure pipe executed');

        return value;

      }

    }


Impure Pipe: An impure pipe will re-run whenever Angular detects a change in the component’s state, even if the input value hasn’t changed.
@Pipe({
  name: 'impureExample',
  pure: false // Set to false to make it impure
})
export class ImpureExamplePipe implements PipeTransform {
  transform(value: any): any {
    console.log('Impure pipe executed');
    return value;
  }
}


In Angular, you can use in-built pipes or create your own.

In-built pipes

Angular provides some basic pipes that can be used.
It comes from the '@angular/common' package.

Some popular ones that can be helpful are:
CurrencyPipe, DatePipe, DecimalPipe, LowerCasePipe, UpperCasePipe and TitleCasePipe

How to use an in-built pipe?

In your ts file, define your variable. In our example, we will use the variable title.
title = 'app works!';

In your html, you can use the pipe as follows:
<h1> {{title | uppercase}} </h1>

The result is how the string title is displayed:

Note. The currency ‘USD’ is added in front because of the currency pipe, and only 10 characters are displayed because of the slide pipe.

Custom pipes

Run the command below to create a pipe file:
ng generate pipe <<pipe-name>>.

For example: ng generate pipe my-custom-pipe. Once executed, the two files below will be created

Open the file ‘my-custom-pipe.pipe.ts. You will see the following boilerplate code provided:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'myCustomPipe'
})
export class MyCustomPipePipe implements PipeTransform {
  transform(value: any, args?: any): any {
    return null;
  }
}


After the default class, you can create the function for your new pipe. In our case, we will create a pipe that will replace spaces in a hyphen. It is important to add the decorator ‘@Pipe’ before the class so that Angular knows what follows will be a pipe. Also, pass the name of the pipe as a parameter in the ‘@Pipe’ decorator. Also, when creating the class, implement ‘PipeTransform’. The resulting class will be as follows:
@Pipe({name: 'removeWhiteSpace'})
export class RemoveWhiteSpacePipe implements PipeTransform {
  transform(value: string): string {
    return value.replace(/\s+/g, '-');
  }
}


The resulting class will be as follows (the full code):
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'myCustomPipe'
})
export class MyCustomPipePipe implements PipeTransform {


  transform(value: any, args?: any): any {
    return null;
  }
}

@Pipe({name: 'removeWhiteSpace'})
export class RemoveWhiteSpacePipe implements PipeTransform {
  transform(value: string): string {
    return value.replace(/\s+/g, '-');
  }
}


In the ts file of your component, create the variable that will hold the value that will be transformed
textWithSpaces = 'This is a text with a lot of spaces that will be transformed';

In the html file of your component, do the following:
<p>{{ textWithSpaces | removeWhiteSpace }}</p>

The result is the following:

Conclusion
An effective and potent method for formatting and transforming data in the templates of your application is to use angular pipes. Without having to code repetitious logic in your components, you can quickly manipulate data types like strings, dates, and numbers by utilizing built-in pipes. More freedom is provided by custom pipelines, which let you design modular, reusable, and maintainable transformation logic that is suited to your particular requirements.

Understanding the distinction between pipes and functions is key to leveraging their full potential. While functions provide a direct way to execute code, pipes offer a declarative approach to handle transformations directly within templates, improving readability and performance.

Whether you're working with Angular’s built-in pipes or creating custom ones, the ability to easily manipulate data in the view layer is a significant advantage in building dynamic and user-friendly applications. By mastering Angular pipes, you can keep your code clean, concise, and aligned with best practices, ultimately leading to more maintainable and scalable applications.

With the knowledge of how to use and create pipes, you’re now equipped to enhance your Angular applications with powerful data transformations, making your development experience more efficient and enjoyable.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in