Powered by Blogger.

Introduction of Angular and AngularJS

No comments :
Here’s a list of common Angular and AngularJS along with detailed examples to help you prepare.
Angular: Angular is a platform and framework for building single-page client applications using HTML, CSS, and JavaScript/TypeScript. It is a complete rewrite of AngularJS, developed by Google. Angular uses TypeScript, which is a superset of JavaScript, offering strong typing, interfaces, and decorators. 
  • Key features of Angular:
  • Two-way data binding
  • Directives for extending HTML capabilities
  • Dependency injection
  • Routing and navigation
  • Components-based architecture
Difference between AngularJS and Angular:
AngularJS  is the original version of Angular, and Angular (2 and above) is a complete rewrite.
Key differences:
Architecture: Angular uses a component-based architecture, whereas AngularJS uses a directive-based architecture.
Language: Angular uses TypeScript, while AngularJS uses JavaScript.
Performance: Angular has better performance because of the use of a new change detection mechanism (in Angular 2+).
Dependency Injection (DI): Angular's DI is more powerful and more flexible than AngularJS.
Angular Components:
In Angular, a component is a building block of the application. It controls a portion of the user interface (UI), with each component consisting of:
  • HTML template (view)
  • CSS styles (view styles)
  • TypeScript class (logic and data)
Example:

In this example, HelloComponent is an Angular component with a template displaying a message.
Data binding in Angular? Explain the types of data binding. Data binding in Angular is the mechanism to synchronize the data between the component and the view. Angular supports several types of data binding:
Interpolation: Binding data from the component to the view.
{{ title }}

Property Binding: Bind an element property to a component property.
<img [src]="imageUrl" alt="Image">

Event Binding: Bind an event (e.g., click) to a method in the component.
<button (click)="onClick()">Click Me</button>

Two-Way Data Binding: Combines property and event binding.
<input [(ngModel)]="username">

Dependency Injection (DI) in Angular?
Dependency Injection (DI) is a design pattern used in Angular to achieve Inversion of Control (IoC). It allows services or objects to be injected into components or other services rather than being created manually inside the component.
Example:

In this example, the DataService is injected into DataComponent via DI, and its method getData() is used in the component.
Angular Routing:
Angular Routing allows you to define routes and navigate between different views or pages in a single-page application (SPA). The routing module helps handle navigation and deep linking.
Example: Define routes in app-routing.module.ts:
Use the router-outlet in app.component.html:
<router-outlet></router-outlet>

Navigating using the routerLink directive:
<a routerLink="/about">About</a>

Service in Angular:
A service is a class in Angular used to handle logic that can be shared across multiple components. Services are commonly used for business logic, data fetching, and state management. Services are injected into components or other services using Angular’s Dependency Injection system.
Example:

In the component, the service is injected:

Directives in Angular:
Directives are special markers in the DOM that allow Angular to modify the DOM structure. There are three types of directives in Angular:
Component Directives: These are the most common type of directives and include templates and logic (e.g., @Component).
Structural Directives: These modify the structure of the DOM (e.g., *ngIf, *ngFor).
Attribute Directives: These change the appearance or behavior of an element (e.g., ngClass, ngStyle).
Example: *ngIf: Conditionally display an element.
<div *ngIf="isVisible">This content is visible.</div>

Observables in Angular:
Observables are a core part of Angular’s reactive programming. They represent a stream of asynchronous events. Angular uses RxJS (Reactive Extensions for JavaScript) for handling asynchronous operations like HTTP requests, user input, or timer events.
Example:

In this example, the HttpClient service returns an Observable, and subscribe() is used to handle the response asynchronously.
Pipes in Angular:
Pipes are used to transform data in the template before it is displayed. Angular provides several built-in pipes like DatePipe, UpperCasePipe, LowerCasePipe, and CurrencyPipe. You can also create custom pipes.
Example:
{{ birthday | date: 'shortDate' }}

In this example, birthday will be transformed into a formatted date using the DatePipe.
You can also create custom pipes:

In the template:
{{ 'Angular' | reverse }}

These are some of the key Angular and AngularJS, along with practical examples. Practicing these concepts and writing code will help you to be more prepared for your Development!

How To Use Predicate In Java 8

1 comment :
In Java 8,
The Predicate is a functional interface that represents a single argument function that returns a boolean value. It is widely used in functional programming, especially when working with streams, as it allows you to define conditions that can be tested.
The Predicate Interface: Let’s look at an example of how to use the @FunctionalInterface annotation in a Spring Boot application:

The Predicate interface contains a method called test(T t) that evaluates a condition and returns a boolean. It also contains some useful default methods like:
  • and(Predicate other): Combines two predicates with a logical AND. 
  • or(Predicate other): Combines two predicates with a logical OR. 
  • negate(): Negates the result of the predicate.
Example 1: Simple Predicate In the following example, a Predicate is used to test whether a number is greater than 10

Example 2: Combining Predicates with and(), or(), and negate() You can combine multiple predicates to create more complex conditions using and(), or(), and negate().

Example 3: Using Predicate with Collections and Streams The Predicate interface is often used with the Streams API to filter collections based on certain conditions.

Example 4: Predicate with isEqual Static Method Java 8 introduces a static method isEqual in the Predicate interface, which is used to create a predicate that checks if two objects are equal.

Example 5: Using Predicate with a List of Objects You can use predicates to filter lists of custom objects. Hare's an example where we filter a list of Person objects based on age.

Summary of Predicate Methods: 
test(T t): Evaluates the predicate on the given argument and returns true or false. 
and(Predicate other): Combines this predicate with another one using logical AND. 
or(Predicate other): Combines this predicate with another one using logical OR. 
negate(): Reverses the result of the predicate (logical NOT). 
isEqual(Object targetRef): Creates a predicate that checks if an object is equal to the given target.
 
* Common Use Cases: 
 Filtering collections with Stream.filter(). Validating input, such as checking if a string matches a pattern or if a number falls within a range. Using complex conditional logic in combination with other predicates.
Predicates are a powerful tool in functional programming and are heavily used in Java 8's Streams API to make code more readable and expressive.

Spring Framework `@ExceptionHandler`

No comments :
In Spring Framework, the `@ExceptionHandler` annotation is used to handle exceptions that occur during the execution of a controller method. This allows you to handle specific exceptions in a centralized manner without cluttering your code with `try-catch` blocks. You can define exception handler methods in your controller or in a global exception handler class.
 
Example of using @ExceptionHandler:
Let’s look at an example of how to use the `@ExceptionHandler` annotation in a Spring Boot application:
Create a custom exception class First, let's define a custom exception that we will handle in the controller.
 


Create a Controller that throws the exception In this step, we’ll create a simple controller that throws a `ResourceNotFoundException` when an endpoint is accessed.
 


Handle the exception using `@ExceptionHandler`  Now, let’s handle the `ResourceNotFoundException` using the `@ExceptionHandler` annotation in the same controller.
 


For Explanation :
  • @RestControllerAdvice: This is a specialized version of @ControllerAdvice that is used for global exception handling in @RestController methods. It allows you to handle exceptions across all controllers.
  •  @ExceptionHandler(ResourceNotFoundException.class): This annotation tells Spring that whenever a `ResourceNotFoundException` is thrown, the `handleResourceNotFoundException` method should handle it. 
  • ResponseEntity: The method returns a ResponseEntity with a custom message and HTTP status code (404 in this case).
 
Running the Application When you run this Spring Boot application and access the /resource/{id} endpoint with an invalid ID (e.g., `/resource/0` or `/resource/-1`), it will return a response like:
HTTP Status: 404 Not Found Body: Resource with ID 0 not found!
Example Output:
  • - When accessing `/resource/1`, it will return "Resource found with ID 1"
  • - When accessing `/resource/0`, it will return a 404 response with the message "Resource with ID 0 not found!".
Advantages of using @ExceptionHandler:
 Centralized exception handling. - Cleaner code with no need for `try-catch` blocks in each controller method. 
 Ability to return custom error responses with HTTP status codes. You can handle multiple exceptions in a similar way by adding more `@ExceptionHandler` methods in the same class, or even define exception handling globally for all controllers using `@ControllerAdvice` instead of `@RestControllerAdvice`.