Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: Understanding @Input(), @Ouput() And @ViewChild() In Angular

clock January 26, 2023 06:32 by author Peter

This article demonstrates how to share data between components using @Input(), @Output(), and @ViewChild().


In Angular, @Input() and @Output() are decorators that allow a component to share data with its parent or child components, respectively. @ViewChild() is a decorator that allows a component to access a child component, directive, or DOM element.

Understanding the use of @Input()
@Input() allows a component to receive data from its parent component. For example, a child component might use @Input() to receive data from its parent component like this:

Here, whenever I added a new entry as "Add Customer", the updated information is passed to the child component (e.g. Customer Table) and the child is acting as a term component. And the parent is acting like smart component.


customer-add.component acts as a Parent Component
In this example, the parent component contains Add customer sections and a sub-component like a customer table. When we click on Add Customer that information being passed to the child component (customers table) and displayed on the table.


customer-table.component acts as a Child Component,

In the above example, the parent component uses the @Input() decorator to bind the "customers" property to a value passed from the parent component.

And the child component uses the @Input() decorator to receive the value passed from the parent component.

So, @Input() decorator is used to pass the data from the parent to the child component with help of property.
Understanding the use of @Output()

@Output() allows a component to emit events to its parent component. For example, a child component might use @Output() to emit an event when a button is clicked like this:

In the above example, whenever we select data from the customer table which acts as a child, that data should pass to the customer’s name textbox which acts as the parent. It’s basically sending data from child to parent. To do that, we need to expose an event with an output decorator.

 

@Output() decorator to listen for an event emitted by the child component, which is then handled in the parent component.


So, @Ouput() decorator is used to pass the data from child to parent with the help of the event.
Understanding the use of @ViewChild()

@ViewChild() allows a component to access a child component or DOM element. For example, a parent component might use @ViewChild() to access a child component like this:

In order to use the @ViewChild() decorator, we need to reference the child component in the parent component's class, and then we can use to query the child component's properties and methods or manipulate the DOM directly.

Another example where @ViewChild() can be used to access the DOM element as like below:

In summary, ViewChild is used to access child components or elements in the template, while @Input and @Output are used to pass data between components. If you need to access a specific child component or element in the template, ViewChild will be more useful, while if you need to pass data between components, @Input and @Output will be more useful.



AngularJS Hosting Europe - HostForLIFE :: How to use Virtual Scrolling using Angular CDK?

clock January 17, 2023 07:09 by author Peter

Sometimes while working with web-based Angular applications you might find yourself in a situation where you need to render thousands of records inside a list. However, rendering that many records directly in the DOM can be a memory-expensive operation and can lead to performance issues or even can cause lag while scrolling through the list.


However, the Angular CDK library, fortunately, comes bundled with a feature called Virtual Scrolling that can be used to fix this issue. This component only the number of records that can fit in the viewport i.e. is visible to the user. And keeps changing the records as the user starts scrolling through the list. This feature was introduced with Angular CDK version 7.

Let's understand this technique in detail with an example.

First, create a dead simple Angular application using Angular CLI.
ng new sample

next, install the Angular CDK package either with Angular CLI or npm.
ng add @angular/cdk

or,

npm install @angular/cdk

Now first inside the app.component.ts file let's generate 500,000 rows and try to render it without the virtual scroll feature.

To generate an array we'll simply use the Array.from method.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  rows: string[] = Array.from(Array(500000)).map((_, i) => `Row #${i}`);
}

Next, we'll try to render the rows in the template.
<div class="box">
  <div class="row" *ngFor="let row of rows">{{ row }}</div>
</div>


We'll also add some styling to the CSS file of this template.
.box {
  height: 250px;
  width: 250px;
  border: 1px solid #e3e3e3;
  overflow: scroll;
}
.row {
  height: 50px;
}


Immediately you'll notice that it is taking a while to render that many rows. And if you try to inspect the element you'll notice that the browser is literally rendering 500,000 rows in the DOM.

Now, let's do the same thing using the Virtual Scrolling technique.

First, we need to import the ScrollingModule inside the AppModule and add it to the imports array.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ScrollingModule } from '@angular/cdk/scrolling';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ScrollingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Importing this module gives us access to cdk-virtual-scroll-viewport components and the cdkVirtualFor directive which we'll be using to implement the virtual scroll strategy.
<cdk-virtual-scroll-viewport itemSize="50" class="box">
  <div class="row" *cdkVirtualFor="let row of rows">
    {{ row }}
  </div>
</cdk-virtual-scroll-viewport>


we're using cdkVirtualFor instead of the ngFor loop to iterate over the rows and itemSize is simply the height of individual elements which in our case is 50px (see the styling for .row class).

As soon as you complete the above implementation you'll notice the rendering time is reduced next to none, and if you inspect the DOM element you'll notice that component has rendered a very limited number of elements and it simply replaces existing rows with new rows as the user scrolls through the list.

 



AngularJS Hosting Europe - HostForLIFE :: Convert Byte Array Into PDF And Open It Inside Custom Dialog box In Angular

clock January 13, 2023 06:41 by author Peter

Mostly on the internet, you can find how to open PDF via window.open(“”) Javascript way.

So what is here?
Well, opening PDF in a separate window is available but is not in our custom control, especially in Angular.

So here we will open this PDF inside our custom dialog (in our control) and can do event firing on the closing of POP up for further business requirements.

Prerequisite(not mandatory)
I am using a ready-made dialog box from prime-ng <p-dialog> control.
But that is not required you can use any material bootstrap or custom div even. This is just to showcase because behind the scene the logic is the same.

Opening PDF In Angular
Opening PDF inside a dialog can be done in a few ways. The Idea/concept behind this is we need to get elementID from DOM and attach our PDF to its inner body. Using below ways
    Using <a href =”url”>.
    Using the same anchor tag by dynamic code and click it.
    Using <iframe/> and appending to DOM body.
    Using .getElementById(“”) and binding to its innerHTML.


Problem
Many times you use “ElementRef, Renderer2” packages which we generally use but you get errors like this:

a. Use @Viewchild()

Alternate Solution
b. Use @inject(document)

Steps
Step 1. Inject the document in the constructor and import it from the library like this.
@Inject(DOCUMENT) private document: Document

Import Library
import { DOCUMENT } from '@angular/common';

Step 2. Use it like this, here I am creating DOM <Frame> element and binding it to Element ID where I want it to display behind the HTML side

Ts Code

Html code

Step 3. It should open like this when you open it inside HTML similar can be done in dialog or popup container:

In Main Body

In POP up

Attachment
Full project will not help as Angular has many packages, so I am giving this simple JavaScript version POC used for angular application. Kindly refer to angular code screenshots (typescript version for reference)

Client-Side coding with a new framework is always fun, Let me know if you have any queries.



Node.js Hosting - HostForLIFE.eu :: How To Setup A Express.js Project?

clock January 6, 2023 06:36 by author Peter

Express.js is one of the most popular frameworks for building web applications using Node.js. It provides features that make creating a robust and scalable web application easy. This step-by-step guide will go over all the steps for setting up an Express.js project from scratch.

Installation is pretty straightforward. Before we get started, you will need to have Node.js installed on your system. You can download the latest version of Node.js from the official website. Once installation is complete, you can run the following commands to verify if Node.js and npm are working correctly on your computer.
npm -v

node -v

You're good to go if you see the versions of Node.js and npm in the command line.

Initializing the project
Let's start by creating a new directory for your project and navigate to it:
mkdir my-express-project
cd my-express-project

Next, initialize the Node.js project by running the following command:
npm init -y

This will create a package.json file in your project directory. The package.json file stores metadata about your project, including the dependencies it needs to run. the -y parameter is used to skip the questionnaire altogether. It'll implicitly set yes to all the questions during the npm init command.

Installing Express.js
To install Express.js, run the following command:
npm install express

This will install Express.js and add it as a dependency in your package.json file.

Creating an entry point for the application
Next, we'll create an entry point for your application. This file will be run when you start the application. First, let's create an src directory in the root of our application and then create a file called index.js inside the src folder and add the following code inside that file:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
    res.send('Hello Express!');
});
app.listen(port, () => {
    console.log(`App is running on port ${port}`);
});

The above code creates an instance of an Express.js app and sets up a route that listens for GET requests to the app's root path (/). When a request is received, it sends a response with the message "Hello Express!". The application is also set to listen on port 3000.

Adding start script
Next, open your package.json file and add look for scripts section. In this section, add the following script.
"scripts": {
  "start": "node src/index.js"
},

Starting the app

Now from the root of your application, run the following command
npm start

This will start the app, and you should see the message "App is running on port 3000" in the console.
To test the app, open your web browser and navigate to http://localhost:3000. You should see the message "Hello Express!" displayed in the browser.

And That's it! I hope you found this article enjoyable. If you've any queries or feedback, feel free to comment.



AngularJS Hosting Europe - HostForLIFE :: How To Create A Download Progress Bar With Angular And Material Design?

clock December 20, 2022 07:03 by author Peter

To create a download progress bar with a percentage in Angular, you can use the HttpClient module to request a server and track the download's progress. Here is an example of how this can be done,
    First, install the @angular/material and @angular/cdk packages in your Angular project:
    npm install @angular/material @angular/cdk


Import the MatProgressBarModule and MatProgressSpinnerModule modules from the @angular/material package in your Angular module:
import { MatProgressBarModule, MatProgressSpinnerModule } from '@angular/material';

@NgModule({
  imports: [
    MatProgressBarModule,
    MatProgressSpinnerModule
  ],
  // ...
})
export class AppModule { }


Now, import the HttpClient module and the HttpEventType enum from the @angular/common/http package:
import { HttpClient, HttpEventType } from '@angular/common/http';

Inject the HttpClient service into your component or service using the constructor:
constructor(private http: HttpClient) {}

Create a function to make the download request and track the progress:
public percentDone: number = 0;

public downloadFile() {
  this.http.get('https://example.com/file.zip', { responseType: 'blob' })
    .subscribe(event => {
      if (event.type === HttpEventType.DownloadProgress) {
        // Update the progress bar with the download percentage
        const this.percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`Downloaded ${this.percentDone}%`);
      } else if (event.type === HttpEventType.Response) {
        // Save the downloaded file
        const file = new Blob([event.body], { type: 'application/zip' });
        const fileURL = URL.createObjectURL(file);
        window.open(fileURL);
      }
    });
}


In your component's template, use the mat-progress-bar and mat-progress-spinner components to display the progress bar and percentage:
<mat-progress-bar mode="determinate" [value]="percentDone"></mat-progress-bar>
<mat-progress-spinner mode="determinate" [value]="percentDone"></mat-progress-spinner>
<p>{{percentDone}}%</p>

You can use the percentDone property to bind to the value attribute of the mat-progress-bar and mat-progress-spinner components, as well as to display the percentage as text.

This is an example of how you can create a material design download progress bar with a percentage in Angular. You can customize the appearance and behaviour of the progress bar and percentage by using the various options and styles available for the mat-progress-bar and mat-progress-spinner components.



European Entity Framework Hosting - HostForLIFE :: Get Started With Entity Framework Core Using SQLite

clock December 14, 2022 06:38 by author Peter

In my previous article Simple Way To Create Sqlite Database, I talked about the choice of the database and I focused on the simplest one which is Sqlite. But even if we choose the right one, we still need to work on the design and on its integration in the application side.


The old way of doing things was to use a database driver in your application, define the connexion and then execute the SQL command and queries from your code. When you get the data from the query execution, you need to parse them and then insert them to your objects. And this was a heavy task.

Later in time appeared Object-Relational Mapping. The ORM.

The ORM is the object-relational Mapping Tool. To make it simple, it's a tool that helps you to translate your database tables to a class Model in your application and vice versa. It also provides you with the methods to perform all the CRUD operation

The approach of creating the database then generating the class model is called Database First. The approach of creating the model in your application and then generating the database is called Code First.

In this article, we will focus on the database first part.

Entity Framework
Entity framework is the most commonly used ORM in .NET projects. It doesn't only allow you to access the database from your application. But also it also simplifies your life by giving you advanced possibilities like managing the concurrency and configuring your model. It has also the advantage of the use of the Language Integrated Query LINQ which is a powerful tool to perform your queries and filters.

Step 1: Nuget packages
    Create a new console project in visual studio.
    Open the commad line: Go to Tools => NuGet Package Manager => Package Manager Console and then you will get the command line displayed in your editor.

Install the required libraries by executing the following commands :

    PM>  Install-Package Microsoft.EntityFrameworkCore.Tools
    PM> install-Package Microsoft.EntityFrameworkCore.Sqlite
    Once you installed all packages you should have the following references in your solution

Step 2: Model generation

    To generate the model, you need to use also the command line
    You need to copy the needed database to your project folder and choose the right mode of copy to output directory:



Now you can generate your classes using the following command. You need to specify the output path, in our case it will be the folder Models
Scaffold-DbContext "Data Source=.\Database\products.db" Microsoft.EntityFrameworkCore.Sqlite -OutputDir Models
if everything is ok, you should get the classes generated under the folder Models and the following message in the package manager console should appear

The warning is there because the generator hardcoded the database's connection string in the code. You need to consider moving it in a protected way to a configuration file. But let's ignore it because it's not the main topic of this article.

Step 3: Check your generated classes
Now you should have the Context that contains the model creation and for each table you will get a class. In our case we have only one entity.

The Context class,
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace EntityFrameworkDbFirst.Models;
public partial class ProductsContext: DbContext {
    public ProductsContext() {}
    public ProductsContext(DbContextOptions < ProductsContext > options): base(options) {}
    public virtual DbSet < Item > Items {
        get;
        set;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code.You can avoid scaffolding the connection string by using the Name = syntax to read it from configuration - see https: //go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseSqlite("Data Source=.\\Database\\products.db");
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity < Item > (entity => {
            entity.HasKey(e => e.Barcode);
            entity.Property(e => e.Barcode).HasColumnType("VARCHAR");
            entity.Property(e => e.Brand).HasColumnType("VARCHAR");
            entity.Property(e => e.Name).HasColumnType("VARCHAR");
            entity.Property(e => e.PruchasePrice).HasColumnType("DOUBLE");
            entity.Property(e => e.SellingPrice).HasColumnType("DOUBLE");
        });
        OnModelCreatingPartial(modelBuilder);
    }
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}


The class Item,
using System;
using System.Collections.Generic;
namespace EntityFrameworkDbFirst.Models;
public partial class Item {
    public string Barcode {
        get;
        set;
    } = null!;
    public string ? Name {
        get;
        set;
    }
    public string ? Brand {
        get;
        set;
    }
    public double ? PruchasePrice {
        get;
        set;
    }
    public double ? SellingPrice {
        get;
        set;
    }
}

Step 4: Write your cruds
Once you have created your model, you can now start performing operations on it. The following code in program.cs allows to add / update or delete an item.
You can test it and then see the results in the database directly.

It's a simple call to every method of the crud. You can play with it by changing the data and adding more controls.
For example if you call the AddItem twice without modifying it you will get an exception related to the constraint of the primary key
// See https://aka.ms/new-console-template for more information
using EntityFrameworkDbFirst.Models;
using System.Runtime.CompilerServices;
using static System.Net.Mime.MediaTypeNames;
using System.Xml.Linq;
try {
    Item item = new Item() {
        Barcode = "B12345678",
            Brand = "Milky Way",
            Name = "Milk",
            PruchasePrice = 20.5,
            SellingPrice = 25.5
    };
    // Uncomment this line if you want to test the delete method
    //DeleteItem("B12345678");
    AddItem(item);
    ////Uncomment this line if you want to test the update method
    //item.SellingPrice = 30;
    //UpdateItem(item);
    Console.WriteLine("Everything is Ok !");
} catch (Exception e) {
    Console.WriteLine(e.Message);
    if (e.InnerException != null) Console.WriteLine(e.InnerException.Message);
}
void AddItem(Item item) {
    using(var db = new ProductsContext()) {
        db.Items.Add(item);
        db.SaveChanges();
    }
}
//Delete the item
void DeleteItem(string Barcode) {
    using(var db = new ProductsContext()) {
        var item = db.Items.Find(Barcode);
        if (item == null) return;
        db.Items.Remove(item);
        db.SaveChanges();
    }
}
//Update the price of the item
void UpdateItem(Item item) {
    using(var db = new ProductsContext()) {
        db.Items.Update(item);
        db.SaveChanges();
    }
}


Step 4: And finally check your database
If you remember, we have set the property of the database in the solution explorer to "Copy if newer" so the file products.db is copied to the binary folder.
Open the database and browse your file then you will see the inserted item. Ensure that you left at least one product after testing the add and the delete



AngularJS Hosting Europe - HostForLIFE :: How To Record A Video Using Angular?

clock December 13, 2022 06:38 by author Peter

Here I recorded a video using MediaRecorder in Angular, So for that follow the below steps for a practical example.


Step 1
Install the @types/dom-mediacapture-record using below npm command
npm i @types/dom-mediacapture-record

No need to import this package into the app.module.ts file, We can directly use in our component.

Step 2
Add the below code to your tsconfig.json file for avoiding some elements-related errors.

tsconfig.json
"compilerOptions": {
    "strictPropertyInitialization": false
  },


If you have already added then avoid it.

Step 3
Now need to import some basic packages from @angular/core and declare the MediaRecorder variable into the component where you want to use it.

Here I am using the app.component.ts file
import {   Component,  ViewChild,  OnInit,  ElementRef} from '@angular/core';
declare var MediaRecorder: any;


Let's share the whole ts file code, Please refer to the below app.component.ts file code

import {Component,  ViewChild,  OnInit,  ElementRef} from '@angular/core';
declare var MediaRecorder: any;
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
    //Video Record and Play By Peter
    videoElement: HTMLVideoElement;
    recordVideoElement: HTMLVideoElement;
    mediaVideoRecorder: any;
    videoRecordedBlobs: Blob[];
    isRecording: boolean = false;
    downloadVideoUrl: string;
    stream: MediaStream;
    @ViewChild('recordedVideo') recordVideoElementRef: ElementRef;
    @ViewChild('liveVideo') videoElementRef: ElementRef;
    constructor() {}
    async ngOnInit() {
        navigator.mediaDevices.getUserMedia({
            video: {
                width: 480
            }
        }).then(stream => {
            this.videoElement = this.videoElementRef.nativeElement;
            this.recordVideoElement = this.recordVideoElementRef.nativeElement;
            this.stream = stream;
            this.videoElement.srcObject = this.stream;
        });
    }
    startVideoRecording() {
        this.videoRecordedBlobs = [];
        let options: any = {
            mimeType: 'video/webm'
        };
        try {
            this.mediaVideoRecorder = new MediaRecorder(this.stream, options);
        } catch (err) {
            console.log(err);
        }
        this.mediaVideoRecorder.start();
        this.isRecording = !this.isRecording;
        this.onDataAvailableVideoEvent();
        this.onStopVideoRecordingEvent();
    }
    stopVideoRecording() {
        this.mediaVideoRecorder.stop();
        this.isRecording = !this.isRecording;
    }
    playRecording() {
        if (!this.videoRecordedBlobs || !this.videoRecordedBlobs.length) {
            return;
        }
        this.recordVideoElement.play();
    }
    onDataAvailableVideoEvent() {
        try {
            this.mediaVideoRecorder.ondataavailable = (event: any) => {
                if (event.data && event.data.size > 0) {
                    this.videoRecordedBlobs.push(event.data);
                }
            };
        } catch (error) {
            console.log(error);
        }
    }
    onStopVideoRecordingEvent() {
        try {
            this.mediaVideoRecorder.onstop = (event: Event) => {
                const videoBuffer = new Blob(this.videoRecordedBlobs, {
                    type: 'video/webm'
                });
                this.downloadVideoUrl = window.URL.createObjectURL(videoBuffer);
                this.recordVideoElement.src = this.downloadVideoUrl;
            };
        } catch (error) {
            console.log(error);
        }
    }
}
Put the same code in your component and verify once it is the correct one.Here I have created some functions regarding our video recording functionality, and If you want to try other mime types then you can use them according to your requirement,Refer to the below support mime types:"video/webm",
"audio/webm",
"video/webm;codecs=vp8",
"video/webm;codecs=daala",
"video/webm;codecs=h264",
"audio/webm;codecs=opus",
"video/mpeg",
Step 4Put the HTML code as shown below app.component,html<div style="text-align:center">
  <h1 style="margin-bottom:30px;">Video Record Using Angular by Peter</h1>
  <video class="video" #liveVideo autoplay controls></video>
  <span class="m-1"></span>
  <video class="video" style="width:480px !important;" controls #recordedVideo></video>
  <br>
  <button class="btn btn-success btn-lg" *ngIf="!isRecording" (click)="startVideoRecording()">Start Recording</button>
  <button class="btn btn-warning btn-lg" *ngIf="isRecording" (click)="stopVideoRecording()">Stop Recording</button>
</div>
If you want to get a better UI then please add the below script to your main index.html, Here I am sharing the whole index.html code you can use only CSS and js.index.html<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Video Record by RG</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>


Let's save and run the app, Browser asks for your camera access give them.
And then click on Start Recording to start and Stop Recording to stop it. Once your recorder has done your recorded video show on right side.

You can play your recorded video by clicking on the play/pause icon.



Node.js Hosting Europe - HostForLIFE :: Explaining NestJS In Depth

clock December 7, 2022 07:21 by author Peter

This would be a series of articles, in this article, we would talk about out-of-box files code explanation and implement new custom APIs (to be covered in the next article)

It will cover the following things,

    What is NestJS? (covered in the previous article)
    Background (covered in the previous article)
    Installation (covered in the previous article)
    Hands-on Lab – Create a sample NestJS project (covered in the previous article)
    Hands-on Lab – Create custom API in the existing NestJS project (covered in the second article)
    In-depth Explanation - Out-of-the-box files (current article)

In-depth Explanation - Out-of-the-box files

Open Visual Code and see the project structure with the following files,

main.ts

    In the below code, the NestFactory method is imported as an entry point of the application. Next, the AppModule is imported from the previously discussed app. module file.
    Secondly, the bootstrap is marked as async and implemented. The main purpose of importing the bootstrap function is to call it for code execution.
    Then, the execution takes when the NestFactory.create() method is called the AppModule is passed as an argument to the root application module.
    This will attach a module by creating a new NestJS instance.
    The next step is to start the server by using the event listener method on the web server with port 3000.
    This method will return a promise indicating that the server has successfully started embarking on the await key.

app.module.ts

  • In the below code snippet, the AppModule is imported as a method, and @Module decorator is imported from @nestjs/ sharing common library. The @Module decorator when passed consists of three properties namely imports, controllers, and providers.
  • The specified controllers in the AppModule should always be the part of the array assigned to the property in the initial stage of the application development because the count of the controller is constrained to AppController which is the root module.
  • And, the services should be made readily available in AppModule and hence be listed in the array assigned to the property of providers.

app.controller.ts
    The below code snippet is a simple demonstration of a controller in NestJS consisting of only one GET route. The class can be made a controller just by adding the @Controller decorator. It is also imported from the @nestjs/ which is a common library for all.
    The point here is to understand clearly that the controller usually relies on a service class.
    In the examples given AppController uses App service to implement the app.services.ts file by importing the corresponding statement that is added at the top.
    However, the process of inserting AppService into AppController is based on the method of Dependency Injection which by default adds the parameter of the same type.
    A default route is then implemented to handle the HTTP GET request through @Get decorator to implement getHello method.
    The method is therefore powered by AppService to fetch data and carry out request and response actions by returning at the same time.

app.services.ts file

  • The below code snippet is a simple demonstration of a controller in NestJS consisting of only one GET route. The class can be made a controller just by adding the @Controller decorator. It is also imported from the @nestjs/ which is a common library for all.
  • The point here is to understand clearly that the controller usually relies on a service class. In the examples given AppController uses Appservice to implement the app.services.ts file by importing the corresponding statement that is added at the top.
  • However, the process of inserting AppService into AppController is based on the method of Dependency Injection which by default adds the parameter of the same type. A default route is then implemented to handle the HTTP GET request through @Get decorator to implement getHello method. The method is therefore powered by AppService to fetch data and carry out request and response actions by returning at the same time.

 

In this article, we talked about all the out-of-the-box files in detail and create a few custom APIs
Stay tuned for the next series of articles, hope you see you guys again soon.

Happy learning!

HostForLIFE.eu Node.js Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



AngularJS Hosting Europe - HostForLIFE :: Create Your First Angular 15 Application

clock December 6, 2022 07:00 by author Peter

We know Angular 15 is released on November 2022, so now in this article, we will see how to create an Angular 15 project. If you have already worked with angular previously you know, angular CLI helps us to build an angular application. Creating a new project in angular is now as simple as installing the Angular CLI and running the ng new command.


What is Angular CLI?
The Angular CLI helps us to create an Angular application and it uses Typescript, it creates an angular application with all the configuration files and the packages in one single command.

It helps us to add features (components, pipe, services, directives, etc.) to existing or new Angular applications.

How to create a new Angular 15 project

To create a new angular 15 project, first we need to set up the system environment

Installing Visual Studio Code
We need an editor to create the application so for that we need to install VS code. It is easy to install and helps us to create an angular application easily. You can download Visual Studio Code from the following link.

Node.Js

Node.js is the open source, cross-platform javascript run time environment.

Go to https://nodejs.org/en/

And install the LTS version
Install the Package Manager

To install Angular and its dependencies, we now need to install Node Package Manager (NPM).

NPM is the node.js package manager for JavaScript, which is automatically installed when we install node.js.

To see the version of NPM, run the below command on the Node.js command prompt like below
Node -v

Go to the Node.js command prompt and install typescript using the below command
Npminstall –gTypescript
Angular CLI (command line interface)

It is a tool that allows us to create a project using the command line argument.

So below is the command to create the latest angular project
npminstall -g @angular/cli@latest

Once the above command runs successfully, now check the latest version of angular and run the below command
Ngversion

Since I was already working on angular 14, so for me only I need to run the Angular CLI command.
Below is the image when my angular version is v14,

Now I ran below CLI command and then check the angular version like the below image
npminstall -g @angular/cli@latest

So this is the way we can upgrade the angular version to the latest version. You can also install the older version of Angular as shown below,

    MDAngular8
    cdAngular8
    npmi @angular/[email protected]

Now to create an Angular 15 application run the below command
NgnewAngular15App

Once you run the above command it will ask to install routing like below, give Y and press enter

After that, it will ask to add CSS like the below,

Once you press enter, it will take a few minutes to create the Angular 15 Application.

So from above, we can see, the angular 15 project creation is in progress.

From the above image, we can see, the angular 15 projects was created successfully. After creating this project, now let's open the VS code, go File tab then select the folder, and go to the directory where we created the angular 15 project, from there, select the angular15 project folder. Once you will load the project, you will see all files in VS code.

Now run the ng serve –o command, it will open the angular15 project like below

 

If you face an error like below then delete ng.ps1 file
PS C:\Users\DELL\Angular15App> ng serve -o

ng : File C:\Users\DELL\AppData\Roaming\npm\ng.ps1 cannot be loaded. The file C:\Users\DELL\AppData\Roaming\npm\ng.ps1 is not digitally signed.
You cannot run this script on the current system. For more information about running scripts and setting execution policies, see
about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.

Then follow the below points then run ng serve –o again,
    Delete ng.ps1 from the directory C:\Users\% usernam%\AppData\Roaming\npm\
    Try to clear the npm cache directory C:\Users\%usernam%\AppData\ Roaming\npm-cache\

Note - Sometimes without clearing the cache also, the above error is resolved.
Now to verify that this application is created in Angular15, just go to the package.json file and see all the libraries are in v15 like below.

To build the application below is the command
ng build

To run the application below is the command
ng serve

after serving the application, go to the browser and enter the below URL, this is the default URL where the angular application run.
http://localhost:4200/



AngularJS Hosting Europe - HostForLIFE :: How To Use HTTP Interceptor In Angular?

clock November 28, 2022 07:16 by author Peter

Angular Interceptor helps us modify the HTTP request by intercepting it before the request is sent to the backend. You can also change the incoming response from the backend. The Interceptor globally captures all incoming and outgoing requests in one place. We can use it to add custom headers to the outgoing request, log the incoming response, etc.

 


What is HTTP Interceptor?
An Angular HTTP interceptor sits between your application and the backend. When the application makes a request, the interceptor sees the request (HttpRequest) before sending it to the backend. You can access the request headers and body by intercepting the request. This allows us to transform the request before sending it to the server.


When the response (HttpResponse) arrives from the backend, interceptors can transform it before forwarding it to the application. One of the main advantages of HTTP interceptors is the ability to add an Authorization header to every request. You can do this manually, but it's tedious and error-prone. Another benefit is the ability to catch and log errors generated by requests.

How to Create Interceptor?
To implement an interceptor, we need to create an injectable service that implements the HttpInterceptor interface.
@Injectable() export class MyHttpInterceptor implements HttpInterceptor {

This class should implement the Intercept method
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //Do the code whatever you want with the HTTP request

    return next.handle(req);
}


This class is exposed in the root module using the HTTP_INTERCEPTORS injection token.
providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: MyHttpInterceptor,
        multi: true
    }
],


Interface: HTTP Interceptor
At the guts of the Interceptor, logic is the HttpInterceptor Interface. we have a tendency to should Implement it in our Interceptor Service.

The interface contains one method Intercept with the subsequent signature
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>

HTTP Request
The first argument is HttpRequest.

HttpRequest is an intercepted outgoing HTTP request. It integrates URLs, methods, headers, body, and various request configurations.

HttpRequest is an immutable class. In any way, we cannot accommodate genuine claims. To make adjustments, we want to duplicate the original request using the HttpRequest.clone

HTTP Handler

The second argument is httpHandler

HttpHandler sends the HttpRequest to the next Controller using the HttpHandler.handleMethod. The next handler can be another interceptor in on Thread or the Http Backend.

Let's see the example

Create MyHttpInterceptor.ts under /app folder and paste the below code
import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor,HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
    constructor() {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req);
    }
}

In the body of the method, you should be able to modify the HttpRequest object. Once done, you can select the HttpHandler.handle method from the HttpHandler with the HttpRequest object. The HttpHandler.handle method calls the fighter thus or sends a request to the main server.

App.Module
Whole code from the app module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { GitHubService } from './github.service';
import {MyHttpInterceptor} from './MyHttpInterceptor';

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


If you have faced any error regarding the import module please check your package.json file and install the required package if not installed.
So, here interceptor-adding process is done let's run the app and you can see every HTTP calls interceptor, You can put the debugger in the interceptor and see.
Let's add content type using interceptor

Content Type Adding
To modify the request we want to clone it using HttpRequest.clone
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });

The header object is also unchanged. Therefore, we need to duplicate it using the headers.set method. The header.set method copies the current header and adds/modifies the new header value and returns the copied header.

We can also use the header.append. The append technique continually appends the header albeit the worth is already present.

And we can also remove the header like the one below shown
req = req.clone({ headers: req.headers.delete('Content-Type','application/json') });

If you want to add authorization token then we can add a token as shown below
const bearerToken: string =authService.Token; // here you can use your service method where get token
if (token) {
    req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + bearerToken) });
}


So we can change or add code as per our requirement like adding logging, modifying response, catching the errors, etc...



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