<?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 Matheus Moreira Luna on Medium]]></title>
        <description><![CDATA[Stories by Matheus Moreira Luna on Medium]]></description>
        <link>https://medium.com/@matheusluna96?source=rss-4ac9eec59448------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LHoMyefQV_ixSp0Ca19nQw.jpeg</url>
            <title>Stories by Matheus Moreira Luna on Medium</title>
            <link>https://medium.com/@matheusluna96?source=rss-4ac9eec59448------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:33:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matheusluna96/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[ Unlocking the Power of Web Components: A Modern Approach to Reusable UI]]></title>
            <link>https://medium.com/@matheusluna96/unlocking-the-power-of-web-components-a-modern-approach-to-reusable-ui-e05b3ddf868b?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/e05b3ddf868b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 19:06:15 GMT</pubDate>
            <atom:updated>2025-04-29T19:08:16.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgRTMTdghOqGmFDYgtWIyg.png" /></figure><p>In the ever-evolving world of web development, <strong>reusability</strong>, <strong>encapsulation</strong>, and <strong>interoperability</strong> have become key pillars of scalable front-end architecture. While modern frameworks like React, Vue, and Angular each bring their own approach to these concepts, there’s a native solution baked right into the browser: <strong>Web Components</strong>.</p><p>Despite being part of the web platform for years, Web Components are still underutilized. This article dives into what they are, why they matter, and how to get started.</p><h3>📦 What Are Web Components?</h3><p>Web Components are a set of standardized APIs that allow developers to create custom, reusable, and encapsulated HTML elements — without relying on external frameworks. They’re composed of four main technologies:</p><ul><li><strong>Custom Elements</strong> — Define your own HTML tags with custom behavior.</li><li><strong>Shadow DOM</strong> — Encapsulate your component’s DOM and styles.</li><li><strong>HTML Templates</strong> — Define reusable chunks of HTML that can be cloned and instantiated.</li><li><strong>ES Modules</strong> — Organize and load your components efficiently with JavaScript modules.</li></ul><p>Together, they enable you to create modular UI elements that work across frameworks and browsers.</p><h3>💡 Why Use Web Components?</h3><p>Here’s why Web Components deserve your attention:</p><p>✅ <strong>Framework Agnostic</strong> — Use them in React, Angular, Vue, or even vanilla JS.<br> ✅ <strong>Encapsulation</strong> — Shadow DOM keeps styles and markup isolated, reducing CSS conflicts.<br> ✅ <strong>Reusability</strong> — Build once, reuse everywhere — even across different projects or teams.<br> ✅ <strong>Native Support</strong> — They run in the browser without polyfills (in most modern environments).<br> ✅ <strong>Future-Proof</strong> — As a web standard, they’ll continue to be supported and improved over time.</p><h3>🧪 Creating Your First Web Component</h3><p>Let’s build a simple &lt;hello-world&gt; component.</p><pre>// hello-world.js<br>class HelloWorld extends HTMLElement {<br>  constructor() {<br>    super();<br>    const shadow = this.attachShadow({ mode: &#39;open&#39; });<br>    shadow.innerHTML = `<br>      &lt;style&gt;<br>        p { color: purple; font-weight: bold; }<br>      &lt;/style&gt;<br>      &lt;p&gt;Hello, Web Components!&lt;/p&gt;<br>    `;<br>  }<br>}</pre><pre>customElements.define(&#39;hello-world&#39;, HelloWorld);</pre><p>To use it in your HTML:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;script type=&quot;module&quot; src=&quot;./hello-world.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;hello-world&gt;&lt;/hello-world&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>And just like that, you’ve created a custom, reusable HTML element — no framework required.</p><h3>🔍 Real-World Use Cases</h3><ul><li><strong>Design Systems</strong> — Many companies use Web Components for their internal design systems.<br> 👉 <a href="https://ionicframework.com/">Ionic</a> and <a href="https://lwc.dev/">Salesforce LWC</a> are great examples.</li><li><strong>Micro Frontends</strong> — Their self-contained nature makes Web Components ideal for micro-frontend architectures.</li><li><strong>Third-Party Widgets</strong> — Web Components are a clean, portable solution when you need embeddable widgets.</li></ul><h3>⚠️ Considerations &amp; Caveats</h3><p>Web Components are powerful, but they come with some trade-offs:</p><ul><li>🔄 <strong>SSR (Server-Side Rendering)</strong> is more complex compared to React or Next.js.</li><li>🛠 <strong>Tooling &amp; Ecosystem</strong> are smaller than major frameworks.</li><li>🧠 <strong>Learning Curve</strong> exists around lifecycle methods and the Shadow DOM.</li></ul><p>That said, they work well <em>alongside</em> frameworks and are a great complement to your toolkit.</p><h3>🚀 Conclusion</h3><p>Web Components aren’t just a curiosity — they’re a powerful, standards-based tool for building scalable and reusable UI components.</p><p>Whether you’re building a design system, creating framework-agnostic components, or just exploring what the browser can do natively, Web Components are worth a look.</p><p>You don’t have to choose between React or Web Components — you can have both.</p><h3>👇 Ready to dive in?</h3><p>Try building a small component and include it in your next project. You might be surprised how often you reach for them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e05b3ddf868b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication and Authorization in Angular]]></title>
            <link>https://medium.com/@matheusluna96/authentication-and-authorization-in-angular-0697ab16e465?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/0697ab16e465</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[auth]]></category>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 19:31:40 GMT</pubDate>
            <atom:updated>2025-02-26T19:31:40.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication and authorization are essential components of modern web applications. In Angular, implementing these mechanisms correctly ensures that users can securely access resources based on their permissions. This article explores how authentication and authorization work in Angular and how to implement them effectively.</p><h3>Authentication vs. Authorization</h3><p>Before diving into the implementation, it is important to distinguish between authentication and authorization:</p><ul><li><strong>Authentication</strong> verifies the identity of a user. It ensures that a user is who they claim to be, typically using a username and password or other authentication methods like OAuth.</li><li><strong>Authorization</strong> determines what a user can do within the application. It controls access to different resources based on user roles or permissions.</li></ul><h3>Implementing Authentication in Angular</h3><h3>1. Setting Up an Authentication Service</h3><p>The authentication service is responsible for handling user login, logout, and token management. A typical implementation uses JSON Web Tokens (JWT) for secure authentication.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { tap } from &#39;rxjs/operators&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthService {<br>  private authUrl = &#39;https://api.example.com/auth&#39;;</pre><pre>  constructor(private http: HttpClient) {}</pre><pre>  login(credentials: { email: string; password: string }): Observable&lt;any&gt; {<br>    return this.http.post&lt;{ token: string }&gt;(`${this.authUrl}/login`, credentials).pipe(<br>      tap(response =&gt; localStorage.setItem(&#39;token&#39;, response.token))<br>    );<br>  }</pre><pre>  logout(): void {<br>    localStorage.removeItem(&#39;token&#39;);<br>  }</pre><pre>  getToken(): string | null {<br>    return localStorage.getItem(&#39;token&#39;);<br>  }</pre><pre>  isAuthenticated(): boolean {<br>    return !!this.getToken();<br>  }<br>}</pre><h3>2. Intercepting HTTP Requests to Add Authentication Headers</h3><p>To include authentication tokens in requests, an HTTP interceptor is needed.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpInterceptor, HttpRequest, HttpHandler } from &#39;@angular/common/http&#39;;</pre><pre>@Injectable()<br>export class AuthInterceptor implements HttpInterceptor {<br>  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler) {<br>    const token = localStorage.getItem(&#39;token&#39;);<br>    if (token) {<br>      req = req.clone({<br>        setHeaders: { Authorization: `Bearer ${token}` }<br>      });<br>    }<br>    return next.handle(req);<br>  }<br>}</pre><p>Then, register the interceptor in app.module.ts:</p><pre>import { HTTP_INTERCEPTORS } from &#39;@angular/common/http&#39;;</pre><pre>@NgModule({<br>  providers: [<br>    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }<br>  ]<br>})<br>export class AppModule {}</pre><h3>Implementing Authorization in Angular</h3><h3>1. Role-Based Route Guards</h3><p>Route guards ensure that only authorized users can access certain routes.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from &#39;@angular/router&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthGuard implements CanActivate {<br>  constructor(private authService: AuthService, private router: Router) {}</pre><pre>  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {<br>    if (this.authService.isAuthenticated()) {<br>      return true;<br>    }<br>    this.router.navigate([&#39;/login&#39;]);<br>    return false;<br>  }<br>}</pre><p>Then, apply the guard to protected routes in app-routing.module.ts:</p><pre>const routes: Routes = [<br>  { path: &#39;dashboard&#39;, component: DashboardComponent, canActivate: [AuthGuard] },<br>  { path: &#39;login&#39;, component: LoginComponent }<br>];</pre><h3>2. Role-Based Access Control (RBAC)</h3><p>To enforce role-based access control, store user roles in the authentication token and validate them:</p><pre>hasRole(role: string): boolean {<br>  const token = this.getToken();<br>  if (!token) return false;<br>  const payload = JSON.parse(atob(token.split(&#39;.&#39;)[1]));<br>  return payload.roles.includes(role);<br>}</pre><p>Then, protect UI elements based on roles:</p><pre>&lt;button *ngIf=&quot;authService.hasRole(&#39;admin&#39;)&quot;&gt;Admin Panel&lt;/button&gt;</pre><h3>Conclusion</h3><p>Authentication and authorization in Angular require a combination of services, route guards, and interceptors to secure an application. Using JWT for authentication and implementing role-based access control ensures that only authorized users can access protected resources. By following these best practices, you can build a secure and scalable Angular application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0697ab16e465" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating WebView in Angular Applications: A Complete Guide]]></title>
            <link>https://medium.com/@matheusluna96/integrating-webview-in-angular-applications-a-complete-guide-e41fb4d79dd4?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/e41fb4d79dd4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[webview]]></category>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 19:29:55 GMT</pubDate>
            <atom:updated>2025-02-21T19:29:55.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>WebView is a powerful component that allows developers to embed web content within their applications. In Angular, WebView can be used to display web pages, hybrid apps, and even interact with native functionality in mobile or desktop applications. This article explores how to integrate WebView in an Angular project, its common use cases, and best practices for seamless implementation.</p><h3>What is WebView?</h3><p>WebView is a browser-like component that enables rendering of web content inside an application rather than opening an external browser. It is commonly used in:</p><ul><li>Hybrid mobile apps (Ionic, Capacitor, Cordova)</li><li>Desktop applications (Electron)</li><li>Displaying external content securely</li><li>Bridging communication between web and native layers</li></ul><h3>Implementing WebView in an Angular App</h3><h3>1. Using WebView in Ionic Angular (Capacitor)</h3><p>Ionic, combined with Capacitor, provides a straightforward way to use WebView in Angular apps for mobile applications.</p><h4>Step 1: Install Capacitor</h4><pre>npm install @capacitor/core @capacitor/cli<br>npm install @capacitor/browser</pre><h4>Step 2: Open Web Content in WebView</h4><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Browser } from &#39;@capacitor/browser&#39;;</pre><pre>@Component({<br>  selector: &#39;app-webview&#39;,<br>  template: &#39;&lt;button (click)=&quot;openWebView()&quot;&gt;Open Web Page&lt;/button&gt;&#39;<br>})<br>export class WebViewComponent {<br>  async openWebView() {<br>    await Browser.open({ url: &#39;https://example.com&#39; });<br>  }<br>}</pre><h3>2. WebView in Electron Angular</h3><p>For desktop applications using Electron, integrating WebView follows a different approach.</p><h4>Step 1: Install Electron Dependencies</h4><pre>npm install electron electron-builder @angular-builders/custom-webpack</pre><h4>Step 2: Add WebView Tag in Angular</h4><pre>&lt;webview src=&quot;https://example.com&quot; style=&quot;width:100%; height:100%;&quot;&gt;&lt;/webview&gt;</pre><h4>Step 3: Enable WebView in Electron’s main.js</h4><pre>const { app, BrowserWindow } = require(&#39;electron&#39;);</pre><pre>let win;<br>app.whenReady().then(() =&gt; {<br>  win = new BrowserWindow({<br>    webPreferences: {<br>      webviewTag: true<br>    }<br>  });<br>  win.loadURL(&#39;http://localhost:4200&#39;);<br>});</pre><h3>3. Handling Communication Between WebView and Angular</h3><p>In hybrid applications, WebView often needs to communicate with Angular components. This can be achieved using message-passing mechanisms like postMessage.</p><h4>Sending Messages from WebView to Angular</h4><pre>window.addEventListener(&#39;message&#39;, (event) =&gt; {<br>  console.log(&#39;Received message:&#39;, event.data);<br>});</pre><h4>Sending Messages from Angular to WebView</h4><pre>const webview = document.querySelector(&#39;webview&#39;);<br>webview?.executeJavaScript(&#39;window.postMessage(&quot;Hello from Angular&quot;, &quot;*&quot;)&#39;);</pre><h3>Best Practices for Using WebView in Angular</h3><ul><li><strong>Enable security measures</strong>: Use Content Security Policy (CSP) to prevent malicious content execution.</li><li><strong>Limit external navigation</strong>: Restrict URL loading to trusted domains.</li><li><strong>Optimize performance</strong>: Avoid loading unnecessary scripts inside WebView.</li><li><strong>Ensure compatibility</strong>: Test WebView behavior on different platforms (Android, iOS, and desktop).</li></ul><h3>Conclusion</h3><p>WebView is a versatile tool for embedding web content in Angular applications. Whether you’re developing mobile apps with Ionic, hybrid solutions with Capacitor, or desktop applications with Electron, WebView provides a seamless way to integrate web-based functionality. By following best practices, you can ensure a secure and efficient WebView implementation in your Angular project.</p><p>Are you using WebView in your Angular applications? Share your experiences and challenges in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e41fb4d79dd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Angular Component Lifecycle]]></title>
            <link>https://medium.com/@matheusluna96/understanding-the-angular-component-lifecycle-87a2f04061cc?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a2f04061cc</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lifecycle]]></category>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 17:09:08 GMT</pubDate>
            <atom:updated>2025-02-17T17:09:08.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular is a powerful framework for building dynamic web applications, and one of its core features is the component-based architecture. Each component in Angular goes through a well-defined lifecycle, which allows developers to hook into different stages of its existence and execute specific logic accordingly. In this article, we will explore the lifecycle of Angular components and understand how to leverage lifecycle hooks effectively.</p><h3>The Component Lifecycle</h3><p>Angular components follow a lifecycle from creation to destruction. The lifecycle is composed of a series of phases, each of which is associated with a specific lifecycle hook. These hooks allow developers to run custom code at particular moments in a component’s existence.</p><h3>Lifecycle Hooks</h3><p>Angular provides several lifecycle hooks, which are methods that can be implemented in a component to perform actions at different stages. Below is an overview of the most commonly used lifecycle hooks:</p><h3>1. ngOnChanges(changes: SimpleChanges)</h3><ul><li>Called before ngOnInit() and whenever an input property changes.</li><li>Provides an object containing the previous and current values of changed properties.</li><li>Useful for reacting to input property updates.</li></ul><h3>2. ngOnInit()</h3><ul><li>Called once after the first ngOnChanges().</li><li>Used for initialization logic, such as fetching data from an API.</li><li>A good place to set up component properties.</li></ul><h3>3. ngDoCheck()</h3><ul><li>Called during every change detection cycle.</li><li>Used for custom change detection, if needed.</li><li>Should be used with caution due to performance implications.</li></ul><h3>4. ngAfterContentInit()</h3><ul><li>Called after Angular projects external content into the component’s view.</li><li>Useful when working with ng-content.</li></ul><h3>5. ngAfterContentChecked()</h3><ul><li>Called after every change detection cycle that checks content projected into the component.</li><li>Used to respond to changes in projected content.</li></ul><h3>6. ngAfterViewInit()</h3><ul><li>Called once after Angular initializes the component’s view and child views.</li><li>Useful for accessing view-related properties, such as @ViewChild() elements.</li></ul><h3>7. ngAfterViewChecked()</h3><ul><li>Called after every change detection cycle that checks the component’s view and child views.</li><li>Used for responding to updates in the view.</li></ul><h3>8. ngOnDestroy()</h3><ul><li>Called just before Angular destroys the component.</li><li>Used for cleanup tasks such as unsubscribing from observables, detaching event listeners, or releasing resources.</li></ul><h3>Example of Lifecycle Hooks in Action</h3><p>Let’s see an example of an Angular component that implements some of these lifecycle hooks:</p><pre>import { Component, OnInit, OnChanges, DoCheck, OnDestroy, Input } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-lifecycle-demo&#39;,<br>  template: &#39;&lt;p&gt;Lifecycle Demo: {{message}}&lt;/p&gt;&#39;<br>})<br>export class LifecycleDemoComponent implements OnInit, OnChanges, DoCheck, OnDestroy {<br>  <br>  @Input() message: string = &#39;&#39;;<br>  <br>  constructor() {<br>    console.log(&#39;Constructor called&#39;);<br>  }</pre><pre>  ngOnChanges() {<br>    console.log(&#39;ngOnChanges called&#39;);<br>  }</pre><pre>  ngOnInit() {<br>    console.log(&#39;ngOnInit called&#39;);<br>  }</pre><pre>  ngDoCheck() {<br>    console.log(&#39;ngDoCheck called&#39;);<br>  }</pre><pre>  ngOnDestroy() {<br>    console.log(&#39;ngOnDestroy called&#39;);<br>  }<br>}</pre><h3>Best Practices for Using Lifecycle Hooks</h3><ol><li><strong>Use </strong><strong>ngOnInit() for initialization</strong> – This is the best place to set up component logic and fetch data.</li><li><strong>Avoid heavy logic in </strong><strong>ngDoCheck()</strong> – Frequent execution may lead to performance issues.</li><li><strong>Unsubscribe in </strong><strong>ngOnDestroy()</strong> – Always clean up subscriptions to prevent memory leaks.</li><li><strong>Use </strong><strong>ngAfterViewInit() for DOM manipulations</strong> – This ensures that the view is fully initialized before accessing elements.</li></ol><h3>Conclusion</h3><p>Understanding the Angular component lifecycle and its hooks is crucial for writing efficient and maintainable applications. By leveraging these hooks correctly, developers can control component behavior, optimize performance, and ensure proper cleanup. Mastering these concepts will help you build robust Angular applications that respond effectively to changes and user interactions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a2f04061cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Interceptors in Angular: A Complete Guide]]></title>
            <link>https://medium.com/@matheusluna96/using-interceptors-in-angular-a-complete-guide-5f1568e22c95?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1568e22c95</guid>
            <category><![CDATA[angular-interceptor]]></category>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 15:36:32 GMT</pubDate>
            <atom:updated>2025-02-12T15:36:32.870Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Interceptors in Angular are powerful tools that allow developers to modify HTTP requests and responses globally. They are particularly useful for handling authentication tokens, logging requests, modifying headers, and managing errors. This article explores how to use interceptors effectively in Angular applications.</p><h3>What Are Interceptors?</h3><p>Interceptors are a feature of Angular’s HttpClientModule that enable developers to intercept and manipulate HTTP requests and responses. They operate at a global level, meaning they automatically apply to every HTTP request sent from an Angular application.</p><h3>Setting Up an Interceptor</h3><p>To create an interceptor, you need to implement the HttpInterceptor interface and override the intercept method.</p><h4>Step 1: Generate an Interceptor</h4><p>You can create an interceptor using Angular CLI:</p><pre>ng generate service interceptors/AuthInterceptor</pre><h4>Step 2: Implement the HttpInterceptor Interface</h4><p>Modify the generated file (auth-interceptor.service.ts) to include the following implementation:</p><pre>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;;</pre><pre>@Injectable()<br>export class AuthInterceptor implements HttpInterceptor {<br>  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    const authToken = localStorage.getItem(&#39;token&#39;);<br>    <br>    if (authToken) {<br>      const clonedReq = req.clone({<br>        setHeaders: {<br>          Authorization: `Bearer ${authToken}`<br>        }<br>      });<br>      return next.handle(clonedReq);<br>    }<br>    <br>    return next.handle(req);<br>  }<br>}</pre><h3>Registering the Interceptor</h3><p>After creating the interceptor, it needs to be registered in the providers array of the app.module.ts file:</p><pre>import { HTTP_INTERCEPTORS } from &#39;@angular/common/http&#39;;<br>import { AuthInterceptor } from &#39;./interceptors/auth-interceptor.service&#39;;</pre><pre>@NgModule({<br>  providers: [<br>    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }<br>  ]<br>})<br>export class AppModule {}</pre><h3>Common Use Cases for Interceptors</h3><ol><li><strong>Adding Authorization Tokens</strong> — Automatically attach authentication tokens to every request.</li><li><strong>Logging Requests and Responses</strong> — Capture request/response details for debugging.</li><li><strong>Handling Global Errors</strong> — Centralize error handling and notify users accordingly.</li><li><strong>Modifying Request Headers</strong> — Add custom headers to all outgoing requests.</li><li><strong>Caching Responses</strong> — Store frequently requested data to reduce API calls.</li></ol><h3>Handling Errors in an Interceptor</h3><p>To globally handle HTTP errors, you can use the catchError operator from RxJS:</p><pre>import { catchError } from &#39;rxjs/operators&#39;;<br>import { throwError } from &#39;rxjs&#39;;</pre><pre>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>  return next.handle(req).pipe(<br>    catchError(error =&gt; {<br>      console.error(&#39;Error occurred:&#39;, error);<br>      return throwError(error);<br>    })<br>  );<br>}</pre><h3>Conclusion</h3><p>Interceptors provide a robust mechanism for handling cross-cutting concerns like authentication, logging, and error handling in Angular applications. By implementing them correctly, you can streamline HTTP requests, improve security, and enhance performance.</p><p>Start using interceptors in your Angular projects today to make your HTTP requests more efficient and manageable!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1568e22c95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using RxJS in Angular: A Comprehensive Guide]]></title>
            <link>https://medium.com/@matheusluna96/using-rxjs-in-angular-a-comprehensive-guide-b1c9e5e9dab7?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1c9e5e9dab7</guid>
            <category><![CDATA[angular-rxjs]]></category>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 18:56:04 GMT</pubDate>
            <atom:updated>2025-02-10T18:56:04.090Z</atom:updated>
            <content:encoded><![CDATA[<p>Reactive programming has become a crucial part of modern web development, and RxJS (Reactive Extensions for JavaScript) is at the heart of this approach in Angular. RxJS provides powerful tools for handling asynchronous operations, event streams, and complex data flows in a more declarative and composable manner. This article explores the fundamentals of using RxJS in Angular and how it enhances application performance and maintainability.</p><h3>What is RxJS?</h3><p>RxJS is a library for reactive programming using Observables, which help manage asynchronous data streams efficiently. It allows developers to compose complex event-driven applications by chaining operators to transform, filter, and manipulate data streams.</p><h3>Why Use RxJS in Angular?</h3><p>Angular heavily relies on RxJS for handling various asynchronous tasks, including:</p><ul><li><strong>HTTP Requests:</strong> Managing data fetching and responses using HttpClient.</li><li><strong>Event Handling:</strong> Reacting to user inputs and UI events efficiently.</li><li><strong>State Management:</strong> Using observables to track application state changes.</li><li><strong>Reactive Forms:</strong> Leveraging RxJS for form controls and validation.</li></ul><h3>Key Concepts in RxJS</h3><h3>1. Observables</h3><p>Observables represent data streams that emit values over time. They can handle synchronous and asynchronous data seamlessly.</p><pre>import { Observable } from &#39;rxjs&#39;;</pre><pre>const observable = new Observable(observer =&gt; {<br>  observer.next(&#39;Hello&#39;);<br>  observer.next(&#39;RxJS&#39;);<br>  observer.complete();<br>});</pre><pre>observable.subscribe(value =&gt; console.log(value));</pre><h3>2. Operators</h3><p>Operators are functions that modify observables by filtering, transforming, or combining them.</p><ul><li><strong>Map:</strong> Transforms emitted values.</li><li><strong>Filter:</strong> Filters values based on conditions.</li><li><strong>MergeMap:</strong> Flattens nested observables.</li><li><strong>SwitchMap:</strong> Cancels previous subscriptions when a new value arrives.</li></ul><p>Example:</p><pre>import { of } from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;</pre><pre>of(1, 2, 3)<br>  .pipe(map(value =&gt; value * 10))<br>  .subscribe(result =&gt; console.log(result));</pre><h3>3. Subjects</h3><p>Subjects are both observables and observers, allowing multicast event broadcasting.</p><pre>import { Subject } from &#39;rxjs&#39;;</pre><pre>const subject = new Subject&lt;number&gt;();<br>subject.subscribe(value =&gt; console.log(&#39;Observer 1:&#39;, value));<br>subject.subscribe(value =&gt; console.log(&#39;Observer 2:&#39;, value));<br>subject.next(42);</pre><h3>4. AsyncPipe</h3><p>Angular provides AsyncPipe to automatically subscribe and unsubscribe from observables in templates.</p><pre>&lt;p&gt;{{ data$ | async }}&lt;/p&gt;</pre><h3>RxJS in Angular Services</h3><p>Services in Angular often use RxJS to handle API calls and data sharing between components.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class DataService {<br>  constructor(private http: HttpClient) {}</pre><pre>  getData(): Observable&lt;any&gt; {<br>    return this.http.get(&#39;https://api.example.com/data&#39;).pipe(<br>      map(response =&gt; response)<br>    );<br>  }<br>}</pre><h3>Best Practices with RxJS in Angular</h3><ol><li><strong>Use Pipeable Operators:</strong> Always use pipe() to compose operators cleanly.</li><li><strong>Manage Subscriptions:</strong> Unsubscribe when necessary using takeUntil or AsyncPipe.</li><li><strong>Use Subjects Wisely:</strong> Prefer BehaviorSubject for state management over simple Subject.</li><li><strong>Handle Errors Gracefully:</strong> Use catchError to prevent application crashes.</li></ol><h3>Conclusion</h3><p>RxJS is a powerful tool for handling asynchronous operations in Angular. By mastering observables, operators, and best practices, developers can build efficient and scalable Angular applications. Understanding and leveraging RxJS can significantly improve code maintainability, readability, and performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1c9e5e9dab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Angular CLI: A Powerful Tool for Angular Developers]]></title>
            <link>https://medium.com/@matheusluna96/understanding-angular-cli-a-powerful-tool-for-angular-developers-9c5fff10c2df?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5fff10c2df</guid>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 14:44:58 GMT</pubDate>
            <atom:updated>2025-02-07T14:44:58.877Z</atom:updated>
            <content:encoded><![CDATA[<p>The development of modern web applications has evolved rapidly, and tools that streamline the process have become essential for developers. One such tool is the <strong>Angular CLI</strong> (Command Line Interface), which simplifies Angular application development by providing a set of powerful commands to manage the entire development lifecycle. In this article, we will explore what Angular CLI is, why it is essential, and how developers can leverage it to enhance their development workflow.</p><h3>What is Angular CLI?</h3><p>Angular CLI is an open-source command-line interface used to automate tasks in the Angular framework. It helps developers create, manage, build, test, and deploy Angular applications in a structured and efficient way. With a set of intuitive commands, Angular CLI abstracts many of the complex, repetitive tasks involved in Angular development, such as project setup, configuration, and build processes.</p><p>By using Angular CLI, developers can focus on writing application code, while the tool handles the repetitive tasks required for a production-ready application.</p><h3>Key Features of Angular CLI</h3><p>Angular CLI offers a variety of features that enhance the development process. Below are some of the most important capabilities:</p><h4>1. Project Setup and Initialization</h4><p>Angular CLI provides an easy way to create a new Angular project using the ng new command. This command initializes a new Angular application with a proper file structure, preconfigured settings, and essential dependencies. It saves time compared to manually setting up the project structure and ensures that best practices are followed from the start.</p><p>Example:</p><pre>ng new my-angular-app</pre><h4>2. Development Server with Hot Reloading</h4><p>Angular CLI includes a development server that serves the application locally using the ng serve command. When running the development server, it watches for changes in the source files and automatically reloads the application in the browser, which improves developer productivity and makes debugging faster.</p><p>Example:</p><pre>ng serve</pre><p>The application can be accessed at http://localhost:4200 by default.</p><h4>3. Code Generation and Scaffolding</h4><p>One of the most useful features of Angular CLI is its ability to generate various Angular components (like components, services, modules, etc.) with predefined templates. This reduces the amount of boilerplate code developers need to write and helps maintain a consistent codebase. The command also generates test files alongside the components to promote a test-driven development approach.</p><p>Example:</p><pre>ng generate component my-component</pre><p>This will create a new component, along with the necessary files (HTML, CSS, TypeScript, and test files), ready to be used in the project.</p><h4>4. Build and Optimization</h4><p>Angular CLI makes it easy to build the project for production or development environments. The ng build command compiles the application, optimizes assets, minifies files, and performs tree-shaking (removes unused code) for production builds. This ensures that the final output is optimized and ready for deployment.</p><p>Example:</p><pre>ng build --prod</pre><h4>5. Testing with Angular CLI</h4><p>Angular CLI supports both unit testing and end-to-end testing. It integrates with tools like <strong>Karma</strong> for unit testing and <strong>Protractor</strong> for end-to-end testing. With the ng test command, developers can run unit tests and check the application’s correctness.</p><p>Example:</p><pre>ng test</pre><p>Similarly, end-to-end tests can be run using:</p><pre>ng e2e</pre><h4>6. Deployment</h4><p>Deploying an Angular application is simplified with Angular CLI. The ng deploy command can be configured to automatically deploy the application to hosting platforms such as Firebase, AWS, or any other compatible service. This streamlines the deployment process and saves developers from manually handling configurations.</p><p>Example:</p><pre>ng deploy --target=production</pre><h3>Advantages of Using Angular CLI</h3><h4>1. Faster Development Process</h4><p>Angular CLI automates many tasks, such as setting up the project, building the application, and managing tests, which can save significant time. Developers can focus on writing business logic and creating features rather than spending time on repetitive tasks.</p><h4>2. Standardized Project Structure</h4><p>Angular CLI enforces a standardized and modular structure for the Angular project, which is especially beneficial when working in teams. This consistency in structure improves maintainability and collaboration across the team.</p><h4>3. Improved Quality</h4><p>Angular CLI encourages best practices and supports tools for unit and end-to-end testing. By generating components with tests and promoting a test-driven development approach, it helps ensure the application’s quality and reliability.</p><h4>4. Scalability</h4><p>As projects grow in size and complexity, Angular CLI’s structure helps manage and scale applications effectively. Whether it’s managing large numbers of components or creating multiple build configurations, Angular CLI ensures scalability while maintaining clarity.</p><h4>5. Community and Ecosystem</h4><p>Angular CLI is actively maintained by the Angular team and has a vibrant community. Regular updates and improvements ensure that the tool remains relevant and compatible with the latest Angular versions and web technologies.</p><h3>How to Install and Use Angular CLI</h3><p>Before using Angular CLI, you need to have <strong>Node.js</strong> and <strong>npm</strong> (Node Package Manager) installed on your system. If they are not installed, you can download and install them from the official <a href="https://nodejs.org/">Node.js website</a>.</p><p>Once Node.js and npm are installed, you can install Angular CLI globally with the following command:</p><pre>npm install -g @angular/cli</pre><p>After installing Angular CLI, you can create a new Angular project:</p><pre>ng new my-app</pre><p>To run the development server, use:</p><pre>cd my-app<br>ng serve</pre><h3>Conclusion</h3><p>Angular CLI is a powerful tool that significantly enhances the Angular development workflow. By automating essential tasks such as project initialization, code generation, building, and testing, Angular CLI allows developers to focus on writing application logic and delivering value faster. It provides a streamlined and consistent development experience, promoting best practices and maintaining high-quality code.</p><p>Whether you are a beginner or an experienced developer, Angular CLI is a must-have tool in your Angular development toolkit. It simplifies the process, improves productivity, and helps you stay focused on building dynamic, robust web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5fff10c2df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The First Steps in Angular: A Beginner’s Guide]]></title>
            <link>https://medium.com/@matheusluna96/the-first-steps-in-angular-a-beginners-guide-7408c6b7ccc5?source=rss-4ac9eec59448------2</link>
            <guid isPermaLink="false">https://medium.com/p/7408c6b7ccc5</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Matheus Moreira Luna]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 18:44:58 GMT</pubDate>
            <atom:updated>2025-02-04T18:44:58.529Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular is a powerful, open-source web application framework developed and maintained by Google. It’s one of the most popular choices for building single-page applications (SPAs) due to its flexibility, performance, and extensive ecosystem. If you’re new to Angular, this article will guide you through the first steps to get started with this robust framework. By the end, you’ll be able to create a simple Angular application and understand the basic concepts that form the foundation of Angular development.</p><h3>1. Setting Up Your Development Environment</h3><p>Before diving into Angular, you’ll need to ensure that you have the necessary tools installed. These include:</p><ul><li><strong>Node.js and npm (Node Package Manager)</strong>: Angular relies on Node.js, and npm is used to install the required packages and dependencies.</li><li><strong>Angular CLI (Command Line Interface)</strong>: The Angular CLI is a powerful tool that helps automate tasks like project creation, development server setup, building, and testing your Angular application.</li></ul><h3>Install Node.js and npm</h3><p>First, download and install Node.js from the official website <a href="https://nodejs.org/">https://nodejs.org/</a>. During installation, npm (Node Package Manager) will also be installed automatically.</p><p>To verify that both Node.js and npm have been installed correctly, open your terminal or command prompt and type:</p><pre>node -v<br>npm -v</pre><p>You should see the version numbers of Node.js and npm.</p><h3>Install Angular CLI</h3><p>Once Node.js and npm are installed, you can install the Angular CLI globally on your system using npm:</p><pre>npm install -g @angular/cli</pre><p>To verify that the Angular CLI is installed, run:</p><pre>ng version</pre><p>This command will display the Angular CLI version along with other important environment information.</p><h3>2. Creating a New Angular Project</h3><p>Now that you have your development environment set up, it’s time to create your first Angular project.</p><p>To create a new Angular application, run the following command:</p><pre>ng new my-angular-app</pre><p>The Angular CLI will prompt you with a series of questions about your project, such as:</p><ul><li><strong>Would you like to add Angular routing?</strong> (Choose “Yes” if you want to implement navigation in your app)</li><li><strong>Which stylesheet format would you like to use?</strong> (You can choose CSS, SCSS, Sass, Less, or Stylus)</li></ul><p>After answering these questions, the Angular CLI will generate a new project folder with all the necessary files and dependencies.</p><p>Once the project is created, navigate to the project folder:</p><pre>cd my-angular-app</pre><h3>3. Running the Development Server</h3><p>To see your application in action, you can run the Angular development server:</p><pre>ng serve</pre><p>By default, the Angular app will be served on http://localhost:4200. Open this URL in your browser, and you should see the default Angular welcome page.</p><h3>4. Understanding the Project Structure</h3><p>After creating your Angular project, you’ll notice several files and folders. Here’s a brief overview of the most important parts of the project structure:</p><ul><li><strong>src/app</strong>: This is where the main code for your application lives. It contains the components, services, and other files that define the functionality of your app.</li><li><strong>src/assets</strong>: This folder holds static assets such as images and stylesheets.</li><li><strong>angular.json</strong>: The configuration file for your Angular project, where you define settings like build options, environment settings, and project structure.</li><li><strong>package.json</strong>: This file contains the project’s dependencies, scripts, and metadata.</li><li><strong>tsconfig.json</strong>: Configuration for TypeScript, which Angular uses for development.</li></ul><h3>5. Creating Your First Angular Component</h3><p>In Angular, components are the building blocks of the application. Each component consists of three main parts:</p><ul><li><strong>HTML template</strong>: Defines the structure and layout of the component.</li><li><strong>CSS/SCSS styles</strong>: Defines the look and feel of the component.</li><li><strong>TypeScript class</strong>: Contains the logic and data for the component.</li></ul><p>To generate a new component, run the following command:</p><pre>ng generate component my-first-component</pre><p>This will create a new component named my-first-component in the src/app directory, along with the necessary files:</p><ul><li>my-first-component.component.ts: Contains the logic and data for the component.</li><li>my-first-component.component.html: The HTML template.</li><li>my-first-component.component.css: The styles for the component.</li></ul><p>Open src/app/app.component.html and add the following code to display your new component:</p><pre>&lt;app-my-first-component&gt;&lt;/app-my-first-component&gt;</pre><p>Then, in the my-first-component.component.ts file, you can modify the component logic, for example, by adding a property to display some dynamic content:</p><pre>import { Component } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-my-first-component&#39;,<br>  templateUrl: &#39;./my-first-component.component.html&#39;,<br>  styleUrls: [&#39;./my-first-component.component.css&#39;]<br>})<br>export class MyFirstComponentComponent {<br>  message: string = &#39;Hello from my first component!&#39;;<br>}</pre><p>In the my-first-component.component.html, bind the message property to the HTML:</p><pre>&lt;p&gt;{{ message }}&lt;/p&gt;</pre><p>Now, when you navigate to http://localhost:4200, you should see the message displayed in your component.</p><h3>6. Working with Data in Angular</h3><p>In Angular, components can exchange data using <strong>properties</strong> and <strong>events</strong>. Here’s a basic example of how to pass data between a parent component and a child component.</p><h3>Parent-Child Component Communication</h3><p>In the parent component, you can define a property and pass it to the child component via <strong>input binding</strong>. For example, update the parent component’s template (app.component.html) like this:</p><pre>&lt;app-my-first-component [message]=&quot;parentMessage&quot;&gt;&lt;/app-my-first-component&gt;</pre><p>In the parent component’s TypeScript file (app.component.ts), define the parentMessage property:</p><pre>export class AppComponent {<br>  parentMessage = &#39;Message from parent!&#39;;<br>}</pre><p>In the child component (my-first-component.component.ts), use the @Input() decorator to receive the data:</p><pre>import { Component, Input } from &#39;@angular/core&#39;;</pre><pre>@Component({<br>  selector: &#39;app-my-first-component&#39;,<br>  templateUrl: &#39;./my-first-component.component.html&#39;,<br>  styleUrls: [&#39;./my-first-component.component.css&#39;]<br>})<br>export class MyFirstComponentComponent {<br>  @Input() message: string = &#39;&#39;;<br>}</pre><p>Now, the child component will display the message passed from the parent.</p><h3>Conclusion</h3><p>Congratulations! You’ve just taken your first steps in Angular. You now know how to set up your development environment, create a new Angular project, generate a component, and pass data between components. These are just the basics, and there’s much more to explore within Angular, such as routing, services, forms, and HTTP requests.</p><p>As you continue learning Angular, it’s important to dive deeper into its core concepts, such as <strong>directives</strong>, <strong>pipes</strong>, and <strong>dependency injection</strong>, which will help you build more complex applications.</p><p>Remember, Angular has a robust community and extensive documentation that can support you as you develop your skills. Keep building, experimenting, and learning — the Angular ecosystem is vast and full of exciting possibilities. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7408c6b7ccc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>