<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joel Sandrakumar on Medium]]></title>
        <description><![CDATA[Stories by Joel Sandrakumar on Medium]]></description>
        <link>https://medium.com/@joel_14492?source=rss-ba89bf144191------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*c8rBJExsRVJZwhhT</url>
            <title>Stories by Joel Sandrakumar on Medium</title>
            <link>https://medium.com/@joel_14492?source=rss-ba89bf144191------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:53:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joel_14492/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Tale of Polly:]]></title>
            <link>https://medium.com/@joel_14492/the-tale-of-polly-e25e9ce272d0?source=rss-ba89bf144191------2</link>
            <guid isPermaLink="false">https://medium.com/p/e25e9ce272d0</guid>
            <dc:creator><![CDATA[Joel Sandrakumar]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 16:15:05 GMT</pubDate>
            <atom:updated>2025-03-05T01:43:17.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Polly in .NET Core</h3><h3>The Resilient and Fault Handling Warrior of .NET Core!</h3><p><strong>Polly</strong>, the <strong>resilience and transient fault-handling library</strong> in .NET Core. Polly is a powerful library that helps developers <strong>handle failures gracefully</strong> by implementing strategies like <strong>retry, circuit breaker, timeout, bulkhead isolation, and fallback</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*wL4zwxPh1TGfc30V.jpeg" /><figcaption>Polly-library in .Net Core</figcaption></figure><h3>Why Use Polly?</h3><p>In microservices and distributed systems, failures like <strong>network timeouts, database connection drops, or API failures</strong> are common. Polly allows you to define <strong>resilient policies</strong> to handle these failures effectively.</p><h3>Key Features of Polly</h3><ol><li><strong>Retry</strong> — Automatically retry an operation if it fails due to transient issues.</li><li><strong>Circuit Breaker</strong> — Stop executing a failing operation for a period to prevent system overload.</li><li><strong>Timeout</strong> — Cancel an operation if it takes too long.</li><li><strong>Fallback</strong> — Provide an alternative response when an operation fails.</li><li><strong>Bulkhead Isolation</strong> — Limit concurrent executions to prevent system overload.</li><li><strong>Cache</strong> — Store results to avoid unnecessary calls.</li></ol><h3>Example Usage in .NET Core</h3><h4><em>Install Polly via NuGet</em></h4><pre>dotnet add package Polly<br>dotnet add package Polly.Extensions.Http</pre><h4>Polly in ASP.NET Core (Using HTTP Client)</h4><p><em>If you’re using </em><strong><em>HttpClient</em></strong><em> in an ASP.NET Core </em><strong><em>microservice</em></strong><em>, you can </em><strong><em>add Polly</em></strong><em> to it easily.</em></p><p>📌 Register Polly in Program.cs</p><pre>using Microsoft.Extensions.DependencyInjection;<br>using Polly;<br>using Polly.Extensions.Http;<br>using System;<br>using System.Net.Http;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddHttpClient(&quot;MyApiClient&quot;, client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;https://example.com/&quot;);<br>})<br>.AddPolicyHandler(Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .WaitAndRetryAsync(3, retryAttempt =&gt; TimeSpan.FromSeconds(retryAttempt)));<br><br>var app = builder.Build();<br>app.Run();</pre><p>✅ Every time your app calls the API, <strong>Polly will retry 3 times before failing</strong>.</p><h4>1️⃣Retry Policy (Try Again If It Fails)</h4><p><em>Polly will </em><strong><em>retry</em></strong><em> the request </em><strong><em>3 times</em></strong><em> before giving up:</em></p><pre>using Polly;<br>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static async Task Main()<br>    {<br>        var httpClient = new HttpClient();<br>        <br>        var retryPolicy = Policy<br>            .Handle&lt;HttpRequestException&gt;()  // Handle HTTP failures<br>            .RetryAsync(3);  // Try again 3 times<br><br>        await retryPolicy.ExecuteAsync(async () =&gt;<br>        {<br>            Console.WriteLine(&quot;Trying to call API...&quot;);<br>            var response = await httpClient.GetAsync(&quot;https://example.com/api&quot;);<br>            response.EnsureSuccessStatusCode(); // Throw error if not successful<br>            Console.WriteLine(&quot;API call succeeded!&quot;);<br>        });<br>    }<br>}</pre><p>✅ If the API <strong>fails</strong>, Polly <strong>tries again</strong> up to <strong>3 times</strong>.</p><h4>2️⃣Wait and Retry (Wait Before Retrying)</h4><p><em>Instead of retrying </em><strong><em>immediately</em></strong><em>, we </em><strong><em>wait</em></strong><em> before trying again.</em></p><pre>var retryPolicy = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .WaitAndRetryAsync(3, retryAttempt =&gt;<br>        TimeSpan.FromSeconds(retryAttempt)); // Wait: 1s, then 2s, then 3s<br><br>await retryPolicy.ExecuteAsync(async () =&gt;<br>{<br>    Console.WriteLine(&quot;Trying...&quot;);<br>    var response = await httpClient.GetAsync(&quot;https://example.com/api&quot;);<br>    response.EnsureSuccessStatusCode();<br>    Console.WriteLine(&quot;Success!&quot;);<br>});</pre><p>✅ <strong>First retry after 1 second, then 2 seconds, then 3 seconds</strong>.<br>✅ <strong>Gives the server time to recover!</strong></p><h4>3️⃣Circuit Breaker (Stop Calling a Failing Service)</h4><p><em>If too many requests </em><strong><em>fail in a row</em></strong><em>, Polly </em><strong><em>stops calling the API for a while</em></strong><em>.</em></p><pre>var circuitBreaker = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(10)); // Break for 10s after 2 failures<br><br>await circuitBreaker.ExecuteAsync(async () =&gt;<br>{<br>    Console.WriteLine(&quot;Calling API...&quot;);<br>    var response = await httpClient.GetAsync(&quot;https://example.com/api&quot;);<br>    response.EnsureSuccessStatusCode();<br>    Console.WriteLine(&quot;API call succeeded!&quot;);<br>});</pre><p>✅ <strong>If API fails, return a default response instead of crashing</strong>.</p><h4>4️⃣ Timeout Policy (Cancel Long-Running Requests)</h4><p><em>If an API call </em><strong><em>takes too long</em></strong><em>, Polly can </em><strong><em>cancel it automatically</em></strong><em>.<br>This prevents your app from waiting forever for a response.</em></p><pre>using Polly;<br>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>var timeoutPolicy = Policy<br>    .TimeoutAsync&lt;HttpResponseMessage&gt;(TimeSpan.FromSeconds(3)); // 3 seconds timeout<br><br>await timeoutPolicy.ExecuteAsync(async () =&gt;<br>{<br>    Console.WriteLine(&quot;Calling API...&quot;);<br>    var response = await new HttpClient().GetAsync(&quot;https://example.com/api&quot;);<br>    Console.WriteLine(&quot;API call succeeded!&quot;);<br>    return response;<br>});</pre><p>✅ If the API <strong>does not respond in 3 seconds</strong>, Polly <strong>cancels</strong> the request.</p><h4>5️⃣Fallback (Return a Default Value If It Fails)</h4><p><em>If the request </em><strong><em>keeps failing</em></strong><em>, Polly can return a </em><strong><em>default value</em></strong><em> instead of an error.</em></p><pre>var fallbackPolicy = Policy&lt;string&gt;<br>    .Handle&lt;HttpRequestException&gt;()<br>    .FallbackAsync(&quot;API is down, using default response&quot;);<br><br>string result = await fallbackPolicy.ExecuteAsync(async () =&gt;<br>{<br>    var response = await httpClient.GetStringAsync(&quot;https://example.com/api&quot;);<br>    return response;<br>});<br><br>Console.WriteLine(result); // Shows &quot;API is down, using default response&quot; if API fails</pre><p>✅ <strong>If API fails, return a default response instead of crashing</strong>.</p><h4>6️⃣ Bulkhead Policy (Limit Concurrent Requests)</h4><p><em>This prevents your system from being </em><strong><em>overloaded</em></strong><em> by limiting the number of </em><strong><em>simultaneous requests</em></strong><em>.<br>If too many requests happen at the same time, the extra ones </em><strong><em>wait or get rejected</em></strong><em>.</em></p><pre>using Polly;<br>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>var bulkheadPolicy = Policy<br>    .BulkheadAsync&lt;HttpResponseMessage&gt;(3, 10); // Allow max 3 requests, queue up to 10<br><br>await bulkheadPolicy.ExecuteAsync(async () =&gt;<br>{<br>    Console.WriteLine(&quot;Processing request...&quot;);<br>    var response = await new HttpClient().GetAsync(&quot;https://example.com/api&quot;);<br>    Console.WriteLine(&quot;Request completed!&quot;);<br>    return response;<br>});</pre><p>✅ Only <strong>3 requests</strong> run at a time, others wait in a queue.<br>✅ If <strong>more than 10 requests</strong> are waiting, Polly <strong>rejects new requests</strong>.</p><h4>7️⃣ Cache Policy (Save Results to Avoid Repeating Requests)</h4><p><em>If an API call </em><strong><em>returns the same data</em></strong><em> often, Polly can </em><strong><em>cache the response</em></strong><em> instead of making new requests.<br>This reduces </em><strong><em>load</em></strong><em> on the API and </em><strong><em>speeds up responses</em></strong><em>.</em></p><pre>using Polly;<br>using Polly.Caching.Memory;<br>using Microsoft.Extensions.Caching.Memory;<br>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>var memoryCache = new MemoryCache(new MemoryCacheOptions());<br><br>var cachePolicy = Policy<br>    .CacheAsync&lt;HttpResponseMessage&gt;(new MemoryCacheProvider(memoryCache), TimeSpan.FromSeconds(60));<br><br>await cachePolicy.ExecuteAsync(async () =&gt;<br>{<br>    Console.WriteLine(&quot;Fetching data...&quot;);<br>    var response = await new HttpClient().GetAsync(&quot;https://example.com/api&quot;);<br>    Console.WriteLine(&quot;Data received!&quot;);<br>    return response;<br>});</pre><p>✅ If the same request happens within <strong>60 seconds</strong>, Polly <strong>returns cached data instead of calling the API again</strong>.</p><h4>8️⃣ Wrap Policy (Combine Multiple Strategies Together)</h4><p><em>You can </em><strong><em>combine</em></strong><em> different Polly policies (like </em><strong><em>Retry + Timeout</em></strong><em> or </em><strong><em>Circuit Breaker + Fallback</em></strong><em>) into one </em><strong><em>Wrap Policy</em></strong><em>.</em></p><pre>var retryPolicy = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .RetryAsync(3);<br><br>var circuitBreakerPolicy = Policy<br>    .Handle&lt;HttpRequestException&gt;()<br>    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(10));<br><br>var timeoutPolicy = Policy<br>    .TimeoutAsync&lt;HttpResponseMessage&gt;(TimeSpan.FromSeconds(5));<br><br>var wrapPolicy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy, timeoutPolicy);<br><br>await wrapPolicy.ExecuteAsync(async () =&gt;<br>{<br>    Console.WriteLine(&quot;Calling API...&quot;);<br>    var response = await new HttpClient().GetAsync(&quot;https://example.com/api&quot;);<br>    response.EnsureSuccessStatusCode();<br>    Console.WriteLine(&quot;Success!&quot;);<br>    return response;<br>});</pre><p>✅ <strong>If API fails, retry up to 3 times.</strong><br>✅ <strong>If it keeps failing, break the circuit for 10 seconds.</strong><br>✅ <strong>If the request takes more than 5 seconds, cancel it.</strong></p><h3>When to Use Polly?</h3><p>✔ <strong>Microservices</strong> — If one service fails, retry instead of crashing<br>✔ <strong>APIs</strong> — Retry if the API is slow or down<br>✔ <strong>Databases</strong> — If the database is busy, retry after a few seconds<br>✔ <strong>Message Queues</strong> — Retry if the message fails to send</p><p>Polly makes your <strong>.NET Core application more resilient</strong> by handling failures <strong>smartly</strong>.🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e25e9ce272d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Microservice Architecture]]></title>
            <link>https://medium.com/@joel_14492/understanding-microservice-architecture-381e62db3f06?source=rss-ba89bf144191------2</link>
            <guid isPermaLink="false">https://medium.com/p/381e62db3f06</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Joel Sandrakumar]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 16:41:31 GMT</pubDate>
            <atom:updated>2025-02-14T01:58:11.811Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Comprehensive Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*As0ssyQoVn-8o_xv1u00jg.jpeg" /><figcaption>Microservices Architecture</figcaption></figure><p>In the rapidly evolving world of software development, microservice architecture has emerged as a game-changer. By decomposing complex applications into smaller, independent services, organizations can achieve greater flexibility, scalability, and maintainability. This article will dive into the core principles of microservice architecture, its components, benefits, challenges, and best practices, helping you understand why it has become the preferred choice for modern application development.</p><h3>What is Microservice Architecture?</h3><p>Microservice architecture is a modern approach to building applications. Unlike traditional monolithic architectures, where all components are integrated into a single codebase, microservices break down the application into a collection of small, independent services. Each service is designed to perform a specific business function and can operate autonomously, communicating with other services via APIs.</p><p>This modular approach offers significant benefits over monolithic systems, such as enhanced scalability, flexibility, and faster development cycles. By decoupling services, organizations can improve resource allocation and optimize system performance, responding to evolving business needs more efficiently.</p><h3>Key Principles of Microservices</h3><h4>1. Service Independence</h4><p>At the heart of microservices is the principle of <strong>service independence</strong>. Each microservice has its own codebase and database, minimizing dependencies between services. This autonomy allows teams to work on different services without disrupting other parts of the system. Service independence also facilitates more frequent updates, quicker deployment cycles, and easier maintenance, as changes to one service don’t affect the entire application.</p><h4>2. Decentralized Data Management</h4><p>Microservices follow the <strong>Database Per Service</strong> pattern, meaning that each service manages its own database. This decentralization allows each service to choose the database technology that best fits its requirements. For example, a service requiring high-speed reads may use a NoSQL database, while another service might benefit from a relational database. This approach improves scalability and enables tailored data solutions for each service.</p><p>However, this independence also presents challenges, particularly around ensuring data consistency across distributed services and managing distributed transactions. Advanced patterns such as <strong>Event Sourcing</strong>, <strong>CQRS</strong> (Command Query Responsibility Segregation), and <strong>Sagas</strong> help maintain data integrity while handling distributed transactions.</p><h4>3. Scalability and Flexibility</h4><p>One of the biggest advantages of microservices is the ability to <strong>scale services independently</strong>. Unlike monolithic applications, where scaling requires duplicating the entire system, microservices enable you to scale only the parts of the application that experience high traffic or demand. This modular scaling not only improves performance but also reduces costs, as you can allocate resources more efficiently.</p><p>Microservices also allow developers to update or deploy new versions of individual services without disrupting the entire system, providing greater flexibility in responding to changing business requirements.</p><h3>Components of Microservices Architecture</h3><h4>1. Service Discovery</h4><p>As microservices often evolve and change, <strong>service discovery</strong> is critical. It allows services to find and communicate with one another dynamically, even if their locations change over time. Tools like <strong>Eureka</strong>, <strong>Consul</strong>, and <strong>Zookeeper</strong> are commonly used to implement service discovery, ensuring that services can dynamically discover and communicate with each other, without the need for hardcoded service locations. These tools often come with additional features like load balancing and fault tolerance, improving system reliability.</p><h4>2. Data Management Challenges</h4><p>Unlike monolithic systems that typically rely on a centralized database, microservices have distributed databases, each managing its own data. This introduces complexities in maintaining data consistency, especially when multiple services need to access or modify the same data. To manage these challenges, organizations use various patterns, including:</p><ul><li><strong>Event Sourcing:</strong> Ensures data consistency by recording all changes as immutable events.</li><li><strong>CQRS:</strong> Separates read and write operations, allowing services to optimize data storage and retrieval.</li><li><strong>Sagas:</strong> Manages distributed transactions by breaking them into smaller, manageable operations, ensuring that data remains consistent even in failure scenarios.</li></ul><h4>3. Design Patterns</h4><p>Microservices come with their own set of challenges that require the use of well-established design patterns. Some key patterns include:</p><ul><li><strong>API Gateway:</strong> Acts as a single entry point for all service requests, managing authentication, routing, and communication between services.</li><li><strong>Continuous Integration / Continuous Deployment (CI/CD):</strong> Automates testing, integration, and deployment processes, enabling faster releases with fewer errors.</li><li><strong>Service Mesh:</strong> Manages communication between microservices, ensuring security, load balancing, and monitoring.</li><li><strong>Event-Driven Architecture:</strong> Microservices often interact with one another through events and asynchronous messaging, improving decoupling and scalability.</li></ul><h3>Key Benefits of Microservices</h3><ul><li><strong>Scalability:</strong> Each microservice can be scaled independently based on demand, ensuring that resources are allocated efficiently.</li><li><strong>Faster Development Cycles:</strong> Independent services allow for faster development, testing, and deployment, reducing time to market.</li><li><strong>Fault Isolation:</strong> Failures in one service do not affect the entire system, as each service operates independently.</li><li><strong>Flexibility in Technology Stack:</strong> Since microservices are loosely coupled, each service can use the best-suited technology for its requirements, enabling developers to use different programming languages, frameworks, and databases.</li></ul><h3>Challenges in Microservices</h3><p>While microservices offer a wealth of benefits, they are not without their challenges. Some common issues organizations face include:</p><ul><li><strong>Complex Inter-Service Communication:</strong> Managing communication between multiple services can become complex, especially when dealing with large-scale systems.</li><li><strong>Data Consistency:</strong> Ensuring data consistency across multiple independent services can be challenging, requiring sophisticated techniques like event sourcing and CQRS.</li><li><strong>Service Deployment and Maintenance:</strong> The decentralized nature of microservices means more services to deploy, monitor, and maintain, which can increase operational complexity.</li><li><strong>Monitoring and Debugging:</strong> Monitoring and debugging in a distributed system requires specialized tools to track service performance and errors.</li></ul><h3>Best Practices for Microservices</h3><ol><li><strong>Keep Services Small &amp; Focused:</strong> Each microservice should handle a specific, narrowly defined business function.</li><li><strong>Automate Deployments:</strong> Implement <strong>CI/CD</strong> pipelines to automate testing, integration, and deployment, ensuring faster and more reliable delivery of updates.</li><li><strong>Design for Failure:</strong> Incorporate resilience patterns such as retries, circuit breakers, and graceful degradation to ensure that your microservices system can withstand failure.</li><li><strong>Use Standardized Communication Protocols:</strong> Adopt standardized communication methods like <strong>REST APIs</strong> or <strong>gRPC</strong> to ensure smooth communication between services.</li></ol><h3>Real-World Example: Netflix</h3><p>Netflix is a prime example of a company that successfully transitioned from a monolithic architecture to a microservices-based system. The migration allowed Netflix to scale its services, increase performance, and provide better fault tolerance. Key technologies used in their microservices implementation include:</p><ul><li><strong>Eureka</strong> for service discovery.</li><li><strong>Hystrix</strong> for fault tolerance.</li><li><strong>Docker</strong> for containerization.</li><li><strong>Kubernetes</strong> for orchestration and scaling.</li></ul><h3>Microservices in Cloud Computing</h3><p>Cloud computing and microservices are a perfect match. Cloud environments provide the flexibility and scalability needed to run distributed systems efficiently. By leveraging cloud-native tools such as <strong>Docker</strong> and <strong>Kubernetes</strong>, organizations can automate the deployment, scaling, and management of their microservices.</p><h3>Conclusion</h3><p>Microservice architecture represents a fundamental shift in how applications are built, deployed, and maintained. It offers unparalleled scalability, flexibility, and resilience, but requires careful planning and execution. By understanding the principles, components, and challenges of microservices, organizations can harness its power to create more agile, efficient, and scalable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=381e62db3f06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of Flutter Widgets]]></title>
            <link>https://medium.com/@joel_14492/the-magic-of-flutter-widgets-613498a3dadc?source=rss-ba89bf144191------2</link>
            <guid isPermaLink="false">https://medium.com/p/613498a3dadc</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[widgets-in-flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Joel Sandrakumar]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 11:30:49 GMT</pubDate>
            <atom:updated>2025-02-13T14:49:59.440Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong><em>Building Apps with Ease</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lqa4NUcNkS95zDhzbbIMjg.png" /></figure><h3>A Journey into Flutter’s Widget Wonderland</h3><p>Imagine you’re an architect, designing a futuristic city. Each building, road, and park is a crucial element of your grand design. In Flutter, <strong>widgets</strong> are your building blocks, allowing you to craft sleek, interactive, and powerful mobile applications.</p><p>If you’re just starting out, don’t worry! By the end of this guide, you’ll be a <strong>Flutter widget wizard</strong>, ready to build real-world apps with confidence. Let’s dive in! 🚀</p><h3>What You’ll Learn</h3><p>🌟 <strong>Uncover the Magic of Flutter Widgets</strong><br>🔄 <strong>Stateless vs. Stateful</strong><br>🖌️ <strong>Craft Stunning UI Layouts</strong><br>⚡ <strong>Ignite User Interaction</strong><br>🔧 <strong>Level Up with Advanced Widgets</strong><br>🎬 <strong>Animate, Gesture, Navigate</strong></p><h3>The Heart of Flutter: Widgets Explained</h3><p><strong><em>Flutter widgets come in two main types:</em></strong></p><h3>🟢 Stateless vs Stateful Widgets</h3><ul><li><strong>StatelessWidget</strong>: Like a billboard, it displays fixed content that doesn’t change.</li><li><strong>StatefulWidget</strong>: Like a smart display, it updates dynamically based on user interaction.</li></ul><h4>🎭 Example: Toggle Text using StatefulWidget</h4><p>Imagine a <strong>billboard</strong> that can switch between two messages with the press of a button. That’s exactly what we’ll build!</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: ToggleTextWidget(),<br>    );<br>  }<br>}<br><br>class ToggleTextWidget extends StatefulWidget {<br>  @override<br>  _ToggleTextWidgetState createState() =&gt; _ToggleTextWidgetState();<br>}<br><br>class _ToggleTextWidgetState extends State&lt;ToggleTextWidget&gt; {<br>  bool isFlutterAwesome = true;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Stateful Widget Example&quot;)),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(<br>              isFlutterAwesome ? &quot;Flutter is Awesome!&quot; : &quot;Let&#39;s Learn Flutter!&quot;,<br>              style: TextStyle(fontSize: 20),<br>            ),<br>            SizedBox(height: 10),<br>            ElevatedButton(<br>              onPressed: () {<br>                setState(() {<br>                  isFlutterAwesome = !isFlutterAwesome;<br>                });<br>              },<br>              child: Text(&quot;Toggle Text&quot;),<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>🏗️ Essential Widgets for Building UI Layouts</h3><h4>1️⃣ Container: The Swiss Army Knife</h4><p>The Container widget is like a <strong>box</strong> where you can add padding, color, and decoration.</p><pre>Container(<br>  padding: EdgeInsets.all(10),<br>  decoration: BoxDecoration(color: Colors.blue, borderRadius: BorderRadius.circular(10)),<br>  child: Text(&quot;Hello, Flutter!&quot;, style: TextStyle(color: Colors.white)),<br>)</pre><h4>2️⃣ Row &amp; Column: Organizing Content</h4><p>Use <strong>Row</strong> for horizontal layouts and <strong>Column</strong> for vertical arrangements.</p><pre>Row(<br>  mainAxisAlignment: MainAxisAlignment.center,<br>  children: [<br>    Icon(Icons.star, color: Colors.yellow),<br>    SizedBox(width: 10),<br>    Text(&quot;5.0 Rating&quot;),<br>  ],<br>)</pre><h4>3️⃣ Stack: Overlapping UI Elements</h4><p>Think of <strong>Stack</strong> as layering objects on top of each other.</p><pre>Stack(<br>  children: [<br>    CircleAvatar(radius: 40, backgroundImage: AssetImage(&quot;assets/profile.jpg&quot;)),<br>    Positioned(bottom: 0, right: 0, child: Icon(Icons.check_circle, color: Colors.green)),<br>  ],<br>)</pre><h3>🎮 Interactive Widgets to Enhance User Experience</h3><h4>1️⃣ Buttons: Click and Interact</h4><ul><li><strong>ElevatedButton</strong> (Raised button with shadow)</li><li><strong>TextButton</strong> (Flat button with text only)</li><li><strong>FloatingActionButton</strong> (Circular button for primary action)</li></ul><pre>ElevatedButton(<br>  onPressed: () =&gt; print(&quot;Button Clicked&quot;),<br>  child: Text(&quot;Click Me&quot;),<br>)</pre><h4>2️⃣ TextField: Accepting User Input</h4><pre>TextField(<br>  decoration: InputDecoration(labelText: &quot;Enter your name&quot;),<br>)</pre><h4>3️⃣ ListView &amp; GridView: Displaying Data</h4><pre>ListView.builder(<br>  itemCount: 5,<br>  itemBuilder: (context, index) {<br>    return ListTile(title: Text(&quot;Item \$index&quot;));<br>  },<br>)</pre><h3>🌟 Advanced &amp; Must-Know Widgets</h3><h4>1️⃣ Card: Beautiful UI Components</h4><pre>Card(<br>  child: ListTile(<br>    leading: Icon(Icons.person),<br>    title: Text(&quot;John Doe&quot;),<br>    subtitle: Text(&quot;Flutter Developer&quot;),<br>  ),<br>)</pre><h4>2️⃣ ExpansionTile: Toggle Visibility</h4><pre>ExpansionTile(<br>  title: Text(&quot;What is Flutter?&quot;),<br>  children: [<br>    Padding(padding: EdgeInsets.all(10), child: Text(&quot;Flutter is an open-source UI framework by Google.&quot;))<br>  ],<br>)</pre><h4>3️⃣ AnimatedContainer: Adding Cool Animations</h4><pre>AnimatedContainer(<br>  duration: Duration(seconds: 1),<br>  height: 100,<br>  width: 100,<br>  color: Colors.blue,<br>)</pre><h4>4️⃣ GestureDetector: Handle Touch Events</h4><pre>GestureDetector(<br>  onTap: () =&gt; print(&quot;Tapped!&quot;),<br>  child: Container(height: 100, width: 100, color: Colors.red),<br>)</pre><h4>5️⃣ PageView: Swipe Between Pages</h4><pre>PageView(<br>  children: [<br>    Container(color: Colors.red),<br>    Container(color: Colors.green),<br>    Container(color: Colors.blue),<br>  ],<br>)</pre><h3>🚀 Final Thoughts</h3><p>Widgets are the soul of Flutter, transforming ideas into stunning mobile applications. By mastering Container, Row, Column, ListView, and Card, you can build sleek and user-friendly interfaces.</p><p><strong>✨ Happy Coding! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=613498a3dadc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Flutter]]></title>
            <link>https://medium.com/@joel_14492/mastering-flutter-1b7c2b04210a?source=rss-ba89bf144191------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b7c2b04210a</guid>
            <category><![CDATA[flutter-roadmap]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-concept]]></category>
            <category><![CDATA[training-flutter-basic]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Joel Sandrakumar]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 00:29:38 GMT</pubDate>
            <atom:updated>2025-02-12T00:33:29.379Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Zero to Hero</strong> roadmap to guide you:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mOO444aE0ysjnJofbxBkQ.png" /></figure><h3>📌 Phase 1: Getting (Beginner Level)</h3><h4>🎯 Goal: Understand the basics of Flutter and Dart</h4><p>✅ <strong>Step 1: Setup &amp; Installation</strong></p><ul><li>Install <strong>Flutter SDK</strong> and <strong>Dart</strong></li><li>Set up <strong>Android Studio</strong> / <strong>VS Code</strong></li><li>Configure <strong>Android Emulator</strong> / <strong>iOS Simulator</strong></li></ul><p>✅ <strong>Step 2: Learn Dart Programming</strong></p><ul><li>Variables, Data Types, and Operators</li><li>Functions and Control Flow (if-else, loops)</li><li>Object-Oriented Programming (Classes, Inheritance, Polymorphism)</li><li>Asynchronous Programming (Future, async/await, Streams)</li></ul><p>✅ <strong>Step 3: Basic Flutter Widgets</strong></p><ul><li><strong>StatelessWidget</strong> &amp; <strong>StatefulWidget</strong></li><li>Layout Basics: Row, Column, Stack, Expanded</li><li>Container, Padding, Align, SizedBox</li><li>Text, Image, Icon, Buttons, TextField</li><li>ListView, GridView, PageView</li></ul><p>✅ <strong>Step 4: Navigation &amp; Routing</strong></p><ul><li><strong>Navigator.push()</strong> &amp; <strong>Navigator.pop()</strong></li><li>Named Routes &amp; Route Generator</li><li>Bottom Navigation Bar &amp; Drawer</li></ul><p>✅ <strong>Step 5: State Management (Beginner Level)</strong></p><ul><li><strong>setState()</strong> for UI updates</li><li>InheritedWidget and Provider (Basic)</li></ul><h3>📌 Phase 2: Intermediate Level (Building Real Apps)</h3><h4>🎯 Goal: Develop complete applications with structured architecture</h4><p>✅ <strong>Step 6: State Management (Advanced Concepts)</strong></p><ul><li>Provider (Advanced)</li><li>Riverpod (Recommended)</li><li>Bloc / Cubit (for complex state management)</li></ul><p>✅ <strong>Step 7: API Integration &amp; Backend Communication</strong></p><ul><li>HTTP Requests using http package</li><li>RESTful API handling (GET, POST, PUT, DELETE)</li><li>JSON Serialization &amp; Parsing (json_serializable)</li></ul><p>✅ <strong>Step 8: Local Database &amp; Storage</strong></p><ul><li>Shared Preferences (For simple key-value storage)</li><li>SQLite &amp; Drift Database (For structured storage)</li><li>Hive (For NoSQL lightweight database)</li></ul><p>✅ <strong>Step 9: UI/UX &amp; Custom Widgets</strong></p><ul><li>Custom Paint &amp; Animations</li><li>Lottie Animations</li><li>Hero Animations &amp; Transitions</li><li>Slivers for advanced scrolling effects</li></ul><p>✅ <strong>Step 10: Firebase Integration</strong></p><ul><li>Firebase Authentication (Google, Email, Phone)</li><li>Firebase Firestore (Realtime Database)</li><li>Firebase Storage (File &amp; Image Uploads)</li><li>Firebase Cloud Messaging (Push Notifications)</li></ul><p>✅ <strong>Step 11: Dependency Injection &amp; Architecture</strong></p><ul><li>Clean Architecture (Layered Structure)</li><li>Dependency Injection with GetIt</li><li>Modularizing Large Projects</li></ul><h3>📌 Phase 3: Advanced Concepts &amp; App Deployment</h3><h4>🎯 Goal: Master performance optimization and publish apps</h4><p>✅ <strong>Step 12: Performance Optimization</strong></p><ul><li>Optimize Rebuilds in UI</li><li>Efficient List Rendering (ListView.builder, Slivers)</li><li>Isolates &amp; Background Services</li></ul><p>✅ <strong>Step 13: Platform Integration &amp; Native Features</strong></p><ul><li>Accessing Camera &amp; Gallery</li><li>Handling Permissions (Permission Handler)</li><li>Using Native Code (Method Channels)</li></ul><p>✅ <strong>Step 14: Testing in Flutter</strong></p><ul><li>Unit Testing (Business Logic)</li><li>Widget Testing (UI Components)</li><li>Integration Testing (End-to-End)</li></ul><p>✅ <strong>Step 15: Continuous Integration &amp; Deployment (CI/CD)</strong></p><ul><li>Automate Build Process (GitHub Actions, Codemagic)</li><li>Play Store &amp; App Store Deployment</li><li>Versioning &amp; App Updates</li></ul><h3>📌 Final Phase: Becoming a Flutter Hero 🚀</h3><h4>🎯 Goal: Build industry-level applications &amp; contribute to open source</h4><p>✅ <strong>Step 16: Build &amp; Launch Full-Fledged Apps</strong></p><ul><li>Clone &amp; Learn from Open-Source Projects</li><li>Create Portfolio Projects (E-commerce, Social Media, Finance Apps)</li><li>Develop Your Own App and Publish It</li></ul><p>✅ <strong>Step 17: Contribute to Open Source &amp; Community</strong></p><ul><li>Contribute to Flutter Repositories on GitHub</li><li>Engage in Flutter Communities &amp; Stack Overflow</li><li>Join Flutter Conferences &amp; Meetups</li></ul><p>✅ <strong>Step 18: Learn Advanced Topics</strong></p><ul><li>Flutter Web &amp; Desktop Development</li><li>Flutter 3+ New Features</li><li>AI &amp; ML Integration with Flutter</li></ul><h3>🚀 Resources to Learn Flutter</h3><p>📘 <strong>Official Docs:</strong> <a href="https://flutter.dev/">Flutter.dev</a><br> 🎥 <strong>YouTube Courses:</strong> Academind, MTechViral, Flutter Mapp<br> 📚 <strong>Books:</strong> “Flutter in Action” &amp; “Pragmatic Flutter”<br> 🎮 <strong>Practice:</strong> <a href="https://flutterchallenges.com/">Flutter Challenges</a>, <a href="https://github.com/tupizz/flutter-ui-challenges">LeetCode UI Challenges</a></p><p>By following this roadmap step by step, you can become a <strong>Flutter expert</strong> and build production-ready apps! 🎯💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b7c2b04210a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Angular Modules]]></title>
            <link>https://medium.com/@joel_14492/mastering-angular-modules-0c0d9657031a?source=rss-ba89bf144191------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c0d9657031a</guid>
            <category><![CDATA[angular-module]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[Joel Sandrakumar]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 08:54:57 GMT</pubDate>
            <atom:updated>2025-02-11T09:24:07.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Boost Efficiency &amp; Code Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0LN6QBXcgIPjLzcp13jFKw.png" /></figure><h3>Introduction</h3><p>Imagine building a house. Would you put the kitchen, bedroom, and bathroom all in one giant space? Of course not! You would separate them into different rooms for organization and functionality. Similarly, in Angular, <strong>modules</strong> help divide your application into logical sections, making development smoother and more efficient.</p><p>In this article, we will explore how <strong>Angular Modules</strong> can boost efficiency, enhance maintainability, and scale your applications seamlessly.</p><h3>What Are Angular Modules?</h3><p>Angular Modules (@NgModule) act as <strong>containers</strong> for different parts of an application, including <strong>components, services, directives, and pipes</strong>. They help keep the application well-structured, reducing complexity as your project grows.</p><p>By default, every Angular application has a <strong>root module</strong>, defined in app.module.ts. However, for better organization, <strong>dividing the app into multiple modules</strong> is a best practice.</p><h4>Example: Understanding Angular Modules with a Shopping Cart App</h4><p>Think of a simple shopping cart application. Instead of putting everything in one module, we can break it down into:</p><ul><li>AppModule (Root Module) → Bootstraps the entire app.</li><li>ProductModule → Manages product-related components and services.</li><li>CartModule → Handles shopping cart functionality.</li><li>UserModule → Manages user authentication and profiles.</li><li>SharedModule → Contains reusable components like buttons, forms, etc.</li></ul><p>Each module has a specific role, keeping the application <strong>clean and manageable</strong>.</p><h3>Why Should You Use Angular Modules?</h3><p>🎯 <strong>Better Code Organization</strong> → Group related functionality together.<br>🚀 <strong>Improved Performance</strong> → Use lazy loading to speed up the app.<br>🔄 <strong>Reusability</strong> → Share components across multiple parts of the app.<br>🔒 <strong>Encapsulation</strong> → Prevent unnecessary dependencies and conflicts.</p><h3>Types of Angular Modules</h3><p>Angular provides different types of modules for better structure:</p><ol><li><strong>Root Module (</strong><strong>AppModule)</strong> → The main module that initializes the application.</li><li><strong>Feature Modules (</strong><strong>ProductModule, </strong><strong>CartModule, </strong><strong>UserModule)</strong> → Manages distinct features.</li><li><strong>Shared Module (</strong><strong>SharedModule)</strong> → Holds reusable components and pipes.</li><li><strong>Core Module (</strong><strong>CoreModule)</strong> → Houses singleton services (e.g., authentication).</li><li><strong>Routing Modules (</strong><strong>AppRoutingModule)</strong> → Manages application navigation.</li></ol><h3>Detailed Example: Creating and Using Angular Modules</h3><p>Let’s say we are building an e-commerce platform. We’ll create a ProductModule to handle all product-related features.</p><h4>Step 1: Create a Feature Module (ProductModule)</h4><p>Run the following Angular CLI command to generate a new module:</p><pre>ng generate module product</pre><h4>This will create a product.module.ts file.</h4><p>Now, let’s define the module:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { ProductListComponent } from &#39;./product-list/product-list.component&#39;;<br>import { ProductDetailComponent } from &#39;./product-detail/product-detail.component&#39;;<br><br>@NgModule({<br>  declarations: [ProductListComponent, ProductDetailComponent],<br>  imports: [CommonModule],<br>  exports: [ProductListComponent]<br>})<br>export class ProductModule {}</pre><p>Here, we:</p><ul><li>Declared ProductListComponent and ProductDetailComponent.</li><li>Imported CommonModule (required for Angular directives like ngIf and ngFor).</li><li>Exported ProductListComponent for use in other modules.</li></ul><h4>Step 2: Implement Lazy Loading for ProductModule</h4><p>Instead of loading the entire module at once, we can lazy load it for better performance.</p><p>Modify app-routing.module.ts:</p><pre>const routes: Routes = [<br>  { path: &#39;products&#39;, loadChildren: () =&gt; import(&#39;./product/product.module&#39;).then(m =&gt; m.ProductModule) }<br>];</pre><p><strong><em>Why Lazy Loading?</em></strong></p><p>🚀 <strong>Reduces Initial Load Time</strong>: Loads only the necessary modules at the right time.<br>⚡ <strong>Enhances Performance</strong>: Improves app speed, especially for large projects.</p><h4>Step 3: Use a Shared Module for Common Components</h4><p>Frequently used components (like buttons, modals) should be placed in a SharedModule.</p><pre>ng generate module shared</pre><p>Now, define shared.module.ts:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { ButtonComponent } from &#39;./button/button.component&#39;;<br><br>@NgModule({<br>  declarations: [ButtonComponent],<br>  exports: [ButtonComponent],<br>  imports: [CommonModule]<br>})<br>export class SharedModule {}</pre><p>Now, we can import SharedModule into ProductModule and use ButtonComponent anywhere.</p><pre>import { SharedModule } from &#39;../shared/shared.module&#39;;<br>@NgModule({<br>  imports: [SharedModule]<br>})<br>export class ProductModule {}</pre><h4>Step 4: Managing Global Services with CoreModule</h4><p>Global services like authentication should be placed in a CoreModule.</p><pre>ng generate module core</pre><p>Define core.module.ts:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@NgModule({<br>  providers: [AuthService]<br>})<br>export class CoreModule {}</pre><p>Now, import CoreModule in AppModule:</p><pre>import { CoreModule } from &#39;./core/core.module&#39;;<br>@NgModule({<br>  imports: [CoreModule]<br>})<br>export class AppModule {}</pre><h3>Common Mistakes to Avoid</h3><p>❌ <strong>Overusing Shared Modules</strong> → Don’t put everything in SharedModule, use feature modules wisely.<br>❌ <strong>Not Using Lazy Loading</strong> → Eagerly loading all modules slows down large applications.<br>❌ <strong>Placing Services in Feature Modules</strong> → Singleton services should go in CoreModule to avoid duplication.</p><h3>Final Project Structure</h3><pre>app/<br> ├── app.module.ts<br> ├── core/<br> │   ├── core.module.ts<br> │   ├── auth.service.ts<br> ├── product/<br> │   ├── product.module.ts<br> │   ├── product-list/<br> │   │   ├── product-list.component.ts<br> │   ├── product-detail/<br> │   │   ├── product-detail.component.ts<br> ├── shared/<br> │   ├── shared.module.ts<br> │   ├── button/<br> │   │   ├── button.component.ts</pre><p>This modular structure ensures that each feature remains independent and reusable.</p><h3>Conclusion</h3><p>By structuring your application with <strong>Angular Modules</strong>, you make it: ✅ <strong>Organized</strong> (separating concerns between different features), ✅ <strong>Efficient</strong> (using lazy loading and reusable modules), ✅ <strong>Scalable</strong> (easier to expand as the project grows).</p><p>Start implementing modules today and take your Angular development to the next level! 🚀</p><p>Start implementing modules today and take your Angular development to the next level! 🚀</p><h3>References</h3><p><strong>📌 Official Angular Guide:</strong> <a href="https://angular.dev/guide/ngmodules/overview">Angular Modules Overview</a><br>📌 <strong>Medium Article:</strong> <a href="https://medium.com/">Boost Your Angular App’s Performance with Lazy Loading</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c0d9657031a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Apps with Lazy Loading]]></title>
            <link>https://medium.com/@joel_14492/boost-your-angular-apps-performance-with-lazy-loading-1cb7b40c6d34?source=rss-ba89bf144191------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cb7b40c6d34</guid>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[angular-lazy-loading]]></category>
            <dc:creator><![CDATA[Joel Sandrakumar]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 07:46:19 GMT</pubDate>
            <atom:updated>2025-02-12T01:13:27.928Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance Performance, Reduce Load Time, and Optimize User Experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGGhlGVmOMOICjhoal4Mtg.jpeg" /></figure><p>Lazy Loading is a game-changing feature in Angular that optimizes your application’s performance by loading feature modules only when they are needed. This article walks you through the basics and implementation of Lazy Loading with a step-by-step guide perfect for beginners.</p><h3>What is Lazy Loading?</h3><p>Imagine an application where certain features are used only occasionally. Wouldn’t it be great if you could load those features only when required? Lazy Loading does just that! Instead of loading all modules upfront, Angular loads specific modules only when the user navigates to a corresponding route, making the app faster and more efficient.</p><h3>Why Should You Use Lazy Loading?</h3><p>Here are some key reasons why Lazy Loading is a must-have in your Angular projects:</p><ol><li><strong>Faster Initial Load</strong>: Reduces the initial load time by downloading only essential modules.</li><li><strong>Resource Efficiency</strong>: Keeps the application lightweight by avoiding unnecessary module loading.</li><li><strong>Scalability</strong>: Modular design makes the app easier to maintain and extend as it grows.</li></ol><h3>The Basics of Lazy Loading in Angular</h3><p>Angular implements Lazy Loading using the router. It loads feature modules dynamically when the user navigates to specific routes. Here’s how it works:</p><ol><li>Create a feature module.</li><li>Set up routing for the module.</li><li>Use the loadChildren property in AppRoutingModule to define lazy-loaded routes.</li></ol><h3>Step-by-Step Guide to Implement Lazy Loading</h3><h4>Step 1: Create a Feature Module</h4><p>To create a feature module, use the Angular CLI. For example, let’s create a User module:</p><pre>ng generate module user --route user --module app.module</pre><p>This command generates a new feature module with:</p><ul><li><strong>user.module.ts</strong></li><li><strong>user-routing.module.ts</strong></li></ul><p><em>The </em><em>--route option automatically sets up lazy-loading for the </em><em>user route.</em></p><h4>Step 2: Configure Routing for the Feature Module</h4><p>Open the UserRoutingModule and define the routes for the User module:</p><pre>// user-routing.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { UserComponent } from &#39;./user.component&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;&#39;, component: UserComponent },<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forChild(routes)],<br>  exports: [RouterModule]<br>})<br>export class UserRoutingModule {}</pre><ul><li>The path: &#39;&#39; route handles navigation to /user.</li><li>The RouterModule.forChild() method is specifically used for feature module routing.</li></ul><h4>Step 3: Set Up Lazy Loading in the AppRoutingModule</h4><p>Modify your AppRoutingModule to include lazy loading using the loadChildren property:</p><pre>// app-routing.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;user&#39;, loadChildren: () =&gt; import(&#39;./user/user.module&#39;).then(m =&gt; m.UserModule) },<br>  { path: &#39;&#39;, redirectTo: &#39;/home&#39;, pathMatch: &#39;full&#39; },<br>  { path: &#39;**&#39;, redirectTo: &#39;/home&#39; },<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule {}</pre><p>The loadChildren property dynamically loads the UserModule only when the /user route is accessed.</p><h4>Step 4: Add a Component to the Feature Module</h4><p>Create a component for the User module:</p><pre>ng generate component user/user</pre><p>Update the UserComponent to include a basic template:</p><pre>// user.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-user&#39;,<br>  template: &#39;&lt;h1&gt;Welcome to the User Module&lt;/h1&gt;&#39;,<br>})<br>export class UserComponent {}</pre><h4>Step 5: Test Lazy Loading</h4><p>Run your application:</p><pre>ng serve</pre><p>Navigate to /user in your browser. Open the browser’s developer tools, go to the Network tab, and observe a separate JavaScript file being loaded for the UserModule. This confirms lazy loading is working.</p><h3>Key Concepts You Should Know</h3><h4>Feature Modules</h4><p>Feature modules encapsulate specific functionality within an Angular application. They help in organizing the app into smaller, manageable units.</p><h4>RouterModule</h4><ul><li><strong>forRoot</strong>: Sets up application-wide routes.</li><li><strong>forChild</strong>: Defines routes specific to feature modules.</li></ul><h4>loadChildren</h4><p>The loadChildren property dynamically imports the feature module. Here’s an example:</p><pre>{ path: &#39;user&#39;, loadChildren: () =&gt; import(&#39;./user/user.module&#39;).then(m =&gt; m.UserModule) }</pre><h3>Benefits of Lazy Loading</h3><ol><li><strong>Optimized Performance</strong>: Minimizes the size of the initial JavaScript bundle.</li><li><strong>Faster Navigation</strong>: Ensures users download only the required code.</li><li><strong>Better Code Organization</strong>: Facilitates modular development and easier maintenance.</li></ol><h3>Complete Example Directory Structure</h3><p>Here’s how the project structure looks after implementing Lazy Loading:</p><pre>src/app/<br>|-- app-routing.module.ts<br>|-- app.module.ts<br>|-- user/<br>    |-- user.module.ts<br>    |-- user-routing.module.ts<br>    |-- user.component.ts</pre><h3>Final Thoughts</h3><p>Lazy Loading is a simple yet effective way to boost your Angular application’s performance. By only loading what’s necessary, you can provide a faster, smoother experience for your users. Follow this guide to start implementing Lazy Loading in your projects today.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cb7b40c6d34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Angular Interceptors]]></title>
            <link>https://medium.com/@joel_14492/mastering-angular-interceptors-a-step-by-step-guide-for-beginners-15ed9721eb66?source=rss-ba89bf144191------2</link>
            <guid isPermaLink="false">https://medium.com/p/15ed9721eb66</guid>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[http-interceptors]]></category>
            <category><![CDATA[angular-http-interceptor]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-interceptor]]></category>
            <dc:creator><![CDATA[Joel Sandrakumar]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 15:55:02 GMT</pubDate>
            <atom:updated>2025-02-12T01:13:57.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Step-by-Step Guide for Beginners</h3><p>Interceptors are one of Angular’s most powerful tools for managing HTTP requests and responses. If you’re new to Angular or just starting with interceptors, this guide will take you from the basics to a comprehensive understanding, complete with a practical example you can implement in your projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQjSpwkMLa4awx1VVNspdQ.png" /><figcaption>Angular Interceptors</figcaption></figure><h3>What Are Interceptors in Angular?</h3><p>Interceptors in Angular are a mechanism to intercept and modify HTTP requests or responses globally before they reach the application or server. They are part of the HttpClient module and are often used for tasks like:</p><ul><li>Adding authentication tokens to requests.</li><li>Logging requests and responses.</li><li>Centralized error handling.</li><li>Caching responses.</li></ul><h3>Why Use Interceptors?</h3><p>Interceptors simplify code by handling cross-cutting concerns (like authentication or error handling) in one place instead of duplicating logic across multiple services or components. <br>They:</p><ul><li>Enhance maintainability.</li><li>Ensure consistent behavior.</li><li>Reduce boilerplate code.</li></ul><h3>Step-by-Step Guide to Interceptors</h3><h4>Step 1: Setting Up an Angular Project</h4><p>If you don’t already have an Angular project, create one:</p><pre>ng new interceptor-demo<br>cd interceptor-demo<br>ng serve</pre><p>Ensure the HttpClientModule is imported into your application:</p><pre>// app.module.ts<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { HttpClientModule } from &#39;@angular/common/http&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, HttpClientModule],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule {}</pre><h3>Step 2: Creating an Interceptor</h3><p>Interceptors in Angular are implemented as services. To create one, generate a new service:</p><pre>ng generate service interceptors/auth</pre><p>Now, implement the HttpInterceptor interface in the newly created service:</p><pre>// src/app/interceptors/auth.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable()<br>export class AuthInterceptor implements HttpInterceptor {<br>  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    // Add an Authorization header to the request<br>    const authToken = localStorage.getItem(&#39;authToken&#39;);<br>    const modifiedRequest = req.clone({<br>      setHeaders: {<br>        Authorization: `Bearer ${authToken}`<br>      }<br>    });<br><br>    return next.handle(modifiedRequest);<br>  }<br>}</pre><h3>Key Points:</h3><ul><li><strong>req.clone()</strong>: Requests are immutable in Angular, so you need to clone them before modification.</li><li><strong>Authorization Header</strong>: This is typically used for passing JWT tokens or API keys.</li></ul><h3>Step 3: Registering the Interceptor</h3><p>To activate the interceptor, provide it in the AppModule:</p><pre>/ src/app/app.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { HttpClientModule, HTTP_INTERCEPTORS } from &#39;@angular/common/http&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { AuthInterceptor } from &#39;./interceptors/auth.service&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, HttpClientModule],<br>  providers: [<br>    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }<br>  ],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule {}</pre><h3>Key Points:</h3><ul><li><strong>HTTP_INTERCEPTORS</strong>: The token used to register interceptors.</li><li><strong>multi: true</strong>: Ensures multiple interceptors can be chained.</li></ul><h3>Step 4: Testing the Interceptor</h3><p>Create a simple service to make HTTP requests:</p><pre>// src/app/services/data.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class DataService {<br>  private apiUrl = &#39;https://jsonplaceholder.typicode.com/posts&#39;;<br><br>  constructor(private http: HttpClient) {}<br><br>  getPosts(): Observable&lt;any&gt; {<br>    return this.http.get(this.apiUrl);<br>  }<br>}</pre><p>Now, call this service from a component:</p><pre>// src/app/app.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./services/data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `&lt;h1&gt;Posts&lt;/h1&gt;&lt;ul&gt;&lt;li *ngFor=&quot;let post of posts&quot;&gt;{{ post.title }}&lt;/li&gt;&lt;/ul&gt;`<br>})<br>export class AppComponent implements OnInit {<br>  posts: any[] = [];<br><br>  constructor(private dataService: DataService) {}<br><br>  ngOnInit(): void {<br>    this.dataService.getPosts().subscribe(<br>      (data) =&gt; (this.posts = data),<br>      (error) =&gt; console.error(&#39;Error fetching posts&#39;, error)<br>    );<br>  }<br>}</pre><p>When you run the application, the interceptor will add the Authorization header to every HTTP request automatically.</p><h3>Step 5: Adding Error Handling</h3><p>You can chain multiple interceptors to handle errors globally. Create a new interceptor:</p><pre>// src/app/interceptors/error.interceptor.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from &#39;@angular/common/http&#39;;<br>import { Observable, throwError } from &#39;rxjs&#39;;<br>import { catchError } from &#39;rxjs/operators&#39;;<br><br>@Injectable()<br>export class ErrorInterceptor implements HttpInterceptor {<br>  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;any&gt; {<br>    return next.handle(req).pipe(<br>      catchError((error: HttpErrorResponse) =&gt; {<br>        console.error(&#39;Error occurred:&#39;, error);<br>        return throwError(error);<br>      })<br>    );<br>  }<br>}</pre><p>Register it in AppModule:</p><pre>providers: [<br>  { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },<br>  { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }<br>]</pre><h3>Summary</h3><ul><li><strong>What Interceptors Do</strong>: Intercept HTTP requests and responses globally.</li><li><strong>Use Cases</strong>: Authentication, logging, error handling, and caching.</li><li><strong>Key Components</strong>:</li></ul><ol><li>Create an interceptor by implementing HttpInterceptor.</li><li>Use req.clone() to modify requests.</li><li>Register the interceptor with HTTP_INTERCEPTORS.</li></ol><p>By following these steps, you can master interceptors in Angular and simplify your HTTP workflows. Interceptors make your code cleaner, more maintainable, and better equipped to handle cross-cutting concerns in your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15ed9721eb66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>