Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: Dynamic JSON Data Handling in Angular

clock May 30, 2023 09:16 by author Peter

You can take the following actions to handle the provided JSON example dynamically in an Angular application:
"Data": ["confidence": 0.9983, "label": "height", "value": "5 FT 7 IN"; "confidence": 0.9971, "label": "squad", "value": "Team A"

Step 1
Create an Angular component: Run the ng produce component dynamicHandling command to create a new component using the Angular CLI.

Step 2
Import the HttpClientModule from @angular/common/http in the app.module.ts file to initiate HTTP queries.
'@angular/common/http' import HttpClientModule;

export class AppModule @NgModule("imports: [ HttpClientModule ], //...")

Step 3
To retrieve the JSON data, send an HTTP request: Import the HttpClient and issue an HTTP GET request to the component's TypeScript file (dynamic-handling.component.ts) to obtain the JSON data.

Component, OnInit, import from '@Angular/core';
'@angular/common/http' import HttpClient;

@Component('app-dynamic-handling', './dynamic-handling.component.html', and './dynamic-handling.component.css') export class DynamicHandlingComponent implements OnInit with the following parameters: jsonData: any;

  private http: HttpClient constructor

  This.http.getany>('your_api_endpoint') in ngOnInit() returns void.(data => subscribe) this.jsonData = data.Data; ); ;



Step 4
To loop through the JSON data in the template, use ngFor: Utilize the ngFor directive in the component's HTML file (dynamic-handling.component.html) to cycle through the jsonData array and dynamically display the results.

"let item of jsonData" in the div *ngFor attribute.'item.label': 'item.value' '/p' '/div'

Step 5
Include the element in the primary template: To display the dynamic handling component, include the app-dynamic-handling> and /app-dynamic-handling> tags in the app.component.html file.
App-dynamic-handling in div, app-dynamic-handling out of div.

The real API endpoint from which you may obtain the JSON data should be substituted for "your_api_endpoint" in Step 3.

As indicated in Steps 2 and 5, be sure to import the HttpClientModule into the app.module.ts file and include the dynamic handling component in the app.component.html main template.

Once the component and template have been configured, the Angular application will issue an HTTP request to retrieve the JSON data and use the ngFor directive in the template to dynamically display the information.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Sort Column (Orderby) Based on Date in Angular 13 using Pipe?

clock May 25, 2023 13:02 by author Peter

To sort an array of objects by a particular date column in ascending or descending order using a custom pipe in Angular, you can modify the date-sort.pipe.ts file as follows:
Custom Pipe (date-sort.pipe.ts)


In Pipe declaration, we can define the name of the filter (pipe), When pipe is true, the pipe is pure, meaning that the transform() method is invoked only when its input arguments change. Pipes are pure by default.

In the transform() method, we can pass the array which needs to be filtered. Property parameter can as based on which date column we need to sort; ordering 'asc' | 'desc' can be also passed.

@Pipe({
  name: 'orderByDate',
  pure:false

})
export class OrderByDatePipe implements PipeTransform {

  transform(array: any[], property: string, order: 'asc' | 'desc'): any[] {
    if (!Array.isArray(array) || !property) {
      return array;
    }

    array.sort((a, b) => {
      const dateA = new Date(a[property]);
      const dateB = new Date(b[property]);

      if (order === 'asc') {
        return dateA.getTime() - dateB.getTime();
      } else {
        return dateB.getTime() - dateA.getTime();
      }
    });

    return array;
  }
}


App.Module.ts for a particular module

Register the custom pipe in the module where you want to use it. For example, open the app.module.ts file and import and add OrderByDatePipe to the declarations array:
@NgModule({
  declarations: [....,....],
  imports: [
    OrderByDatePipe
  ],
  providers: [ ....]


For use across Application

1. We can use Share.Module.ts, Register the custom pipe in share module,
@NgModule({
  declarations: [
    OrderByDatePipe
  ],
  imports: [
    CommonModule
  ]
  ,exports:[
   OrderByDatePipe

  ]
})


2. We can import ShareModule in whether we want to use it inside any module.
@NgModule({
  declarations: [...,.... ],
  imports: [
    .....
    SharedModule,
    ....
  ],
  providers: [ .....]


App.Component.html
    In your component's template, pass the desired date column and order ('asc' or 'desc') as parameters to the OrderByDatePipe :
    Make sure to replace 'scheduleStartDate' with the actual name of the date column in your array of objects.

By providing the specific property/column to the orderByDate pipe, you can sort the array based on that property's date values in either ascending or descending order.
<div *ngFor="let schedule of CurrentSchedule | orderByDate:'scheduleStartDate':'asc'">
 ....
....
</div>
 <div *ngFor="let schedule of CurrentSchedule | orderByDate:'scheduleStartDate':'desc'">
 ....
....
</div>



AngularJS Hosting Europe - HostForLIFE.eu :: Real-Time Communication Made Simple: Angular Demonstrating Web Sockets

clock May 23, 2023 07:12 by author Peter

Web Sockets
Web sockets are a protocol that facilitates bidirectional, full-duplex communication between clients and servers over a single, persistent connection. In contrast to conventional HTTP requests, which are stateless and request-response based, web sockets enable event-driven communication in real time. They are especially useful for applications requiring real-time updates, such as messaging applications, collaborative tools, and real-time dashboards.

Setting Up an Angular Project
To begin using web sockets in Angular, we must create a new project. Let's utilize the Angular CLI to scaffold the application's structure and install any necessary dependencies. Open your terminal or command prompt and proceed as follows:

Install Angular CLI if it is not already installed.

npm install -g @angular/cli

Step 2. Create a new Angular project.
ng new websocket-demo
cd websocket-demo


Establishing a Web Socket Connection
Now that we have our Angular project set up let's establish a web socket connection. We'll create a service that wraps the WebSocket API and handles the connection lifecycle. Open the terminal/command prompt and navigate to the project's root directory. Then, follow these steps.

1. Generate a WebSocket service.
ng generate service websocket

2. Open the newly generated service file (websocket.service.ts) and replace its content with the following code.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  private socket: WebSocket;

  constructor() { }

  connect(): void {
    this.socket = new WebSocket('wss://your-websocket-url');

    this.socket.onopen = () => {
      console.log('WebSocket connection established.');
    };

    this.socket.onmessage = (event) => {
      console.log('Received message:', event.data);
    };

    this.socket.onclose = (event) => {
      console.log('WebSocket connection closed:', event);
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
  }

  sendMessage(message: string): void {
    this.socket.send(message);
  }

  closeConnection(): void {
    this.socket.close();
  }
}


3. Replace 'wss://your-websocket-url' in the connect() the method with the actual WebSocket URL you want to connect to.

Sending and Receiving Data

With our web socket service in place, we can now send and receive data between the client and server. Open the component where you want to use the web socket service (e.g., app.component.ts) and follow these steps.

Import the WebSocket service
import { Component } from '@angular/core';
import { WebsocketService } from './websocket.service';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class AppComponent {
  constructor(private websocketService: WebsocketService) {}

  sendMessage(): void {
    const message = 'Hello, WebSocket!';
    this.websocketService.sendMessage(message);
  }
}

In the same component file (e.g., app.component.ts), add the following code to receive messages from the server.
@Component({
  // Component configuration...
})
export class AppComponent implements OnInit {
  receivedMessages: string[] = [];

  constructor(private websocketService: WebsocketService) {}

  ngOnInit(): void {
    this.websocketService.connect();
    this.websocketService.messageReceived.subscribe((message: string) => {
      this.receivedMessages.push(message);
    });
  }

  sendMessage(): void {
    const message = 'Hello, WebSocket!';
    this.websocketService.sendMessage(message);
  }
}

In the component template (app.component.html), display the received messages.
<button (click)="sendMessage()">Send Message</button>

<ul>
  <li *ngFor="let message of receivedMessages">{{ message }}</li>
</ul>

Now, when the sendMessage() the method is called, it will send a message to the server using the web socket service. The received messages from the server are stored in the receivedMessages array and displayed in the component template.

Handling Errors and Disconnections

To handle errors and disconnections gracefully, let's make some modifications to our existing code. Open the websocket.service.ts file and follow these steps,

-  Import the Subject class from RxJS to handle the stream of received messages. Add the following line at the top of the file after the existing imports.
import { Subject } from 'rxjs';

-  Inside the WebsocketService class, declare a new messageReceived property of type Subject<string>. This will be used to emit and subscribe to the received messages:
messageReceived: Subject<string> = new Subject<string>();

-  In the onmessage event handler, modify the code to emit the received message through the messageReceived subject.
this.socket.onmessage = (event) => {
  const message = event.data;
  console.log('Received message:', message);
  this.messageReceived.next(message);
};


By implementing these changes, we are now using the messageReceived subject to emit and subscribe to the received messages in our Angular component. This allows us to handle and display the messages in real time.

In this article, we have explored how to implement web sockets in an Angular project to enable real-time communication between clients and servers. We covered the fundamentals of web sockets, including setting up an Angular project, establishing a web socket connection, sending and receiving data, and handling errors and disconnections.



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