<?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 Bhaskar on Medium]]></title>
        <description><![CDATA[Stories by Bhaskar on Medium]]></description>
        <link>https://medium.com/@bhaskarpaleti70366?source=rss-ef8d79a19685------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YguvCu35WYgKoHmx</url>
            <title>Stories by Bhaskar on Medium</title>
            <link>https://medium.com/@bhaskarpaleti70366?source=rss-ef8d79a19685------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:40:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhaskarpaleti70366/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[NgRx: The Complete Guide Nobody Gave You Before You Started Using It]]></title>
            <link>https://medium.com/@bhaskarpaleti70366/ngrx-the-complete-guide-nobody-gave-you-before-you-started-using-it-4bfd62aa1c49?source=rss-ef8d79a19685------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bfd62aa1c49</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Bhaskar]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 11:22:42 GMT</pubDate>
            <atom:updated>2026-09-04T11:22:42.349Z</atom:updated>
            <content:encoded><![CDATA[<p>Master Angular’s most misunderstood state management library — from actions to effects, with clear explanations and real code examples.</p><h3>Why State Management Matters</h3><p>Before diving in, let’s answer the obvious question:</p><p>As an Angular app grows, data starts living everywhere — inside components, passed through @Input()/@Output() chains, duplicated across services, and mutated in ways nobody can trace. You end up with:</p><ul><li><strong>The same API call fired from three different components</strong>, because nobody knew the data was already loaded</li><li><strong>A bug where updating state in one place doesn’t reflect in another</strong>, because two components hold two different copies of “the same” data</li><li><strong>No idea what changed the state</strong>, because fifteen services can all mutate the same subject</li></ul><p>NgRx solves this by giving your application <strong>one source of truth</strong>, a <strong>strict, predictable way to change it</strong>, and a <strong>clear trail of every state change</strong> — so at any point you can answer “what happened, and why.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1f1mfD8KYEUYXF7gZNueA.png" /></figure><p>In Angular, NgRx is built on the <strong>Redux pattern</strong>, adapted for RxJS. Understanding the pieces — Store, Actions, Reducers, Selectors, and Effects — is essential for building apps that stay maintainable as they grow.</p><h3>1. Core Concepts &amp; Setup</h3><h3>What is the Store?</h3><p>The <strong>Store</strong> is a single, centralized, immutable object that holds your entire application’s state. Think of it as a giant, read-only JSON object that every component can look into — but nobody is allowed to write into directly.</p><h3>What are Actions?</h3><p><strong>Actions</strong> are plain objects that describe <em>what happened</em> — not what should change. They’re the only way to communicate an intent to modify the store.</p><pre>// user.actions.ts<br>import { createAction, props } from &#39;@ngrx/store&#39;;<br><br>export const loadUsers = createAction(&#39;[User Page] Load Users&#39;);<br><br>export const loadUsersSuccess = createAction(<br>  &#39;[User API] Load Users Success&#39;,<br>  props&lt;{ users: User[] }&gt;()<br>);<br><br>export const loadUsersFailure = createAction(<br>  &#39;[User API] Load Users Failure&#39;,<br>  props&lt;{ error: string }&gt;()<br>);</pre><p>Think of an action as a receipt: it tells the store <em>this event occurred</em>, with whatever data came along with it.</p><h3>What are Reducers?</h3><p>A <strong>reducer</strong> is a pure function that takes the current state and an action, and returns a <em>new</em> state. It never mutates the existing state — it always returns a fresh object.</p><pre>// user.reducer.ts<br>import { createReducer, on } from &#39;@ngrx/store&#39;;<br>import { loadUsers, loadUsersSuccess, loadUsersFailure } from &#39;./user.actions&#39;;<br><br>export interface UserState {<br>  users: User[];<br>  loading: boolean;<br>  error: string | null;<br>}<br><br>export const initialState: UserState = {<br>  users: [],<br>  loading: false,<br>  error: null,<br>};<br><br>export const userReducer = createReducer(<br>  initialState,<br>  on(loadUsers, (state) =&gt; ({ ...state, loading: true, error: null })),<br>  on(loadUsersSuccess, (state, { users }) =&gt; ({ ...state, users, loading: false })),<br>  on(loadUsersFailure, (state, { error }) =&gt; ({ ...state, error, loading: false }))<br>);</pre><p><strong>The rule of thumb:</strong> a reducer must be pure. No HTTP calls, no Date.now(), no random values, no mutation. Same input, same output — every time.</p><h3>Project Setup</h3><pre>ng add @ngrx/store<br>ng add @ngrx/effects<br>ng add @ngrx/store-devtools<br>ng add @ngrx/entity     # optional, covered later</pre><p>Registering a feature slice:</p><pre>// app.config.ts (standalone) or app.module.ts<br>import { provideStore } from &#39;@ngrx/store&#39;;<br>import { provideEffects } from &#39;@ngrx/effects&#39;;<br>import { userReducer } from &#39;./state/user.reducer&#39;;<br>import { UserEffects } from &#39;./state/user.effects&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideStore({ users: userReducer }),<br>    provideEffects([UserEffects]),<br>  ],<br>};</pre><h3>2. Selectors — Reading From the Store</h3><h3>Why Selectors Instead of Direct Access?</h3><p>You could technically do store.select(state =&gt; state.users.users) everywhere. But that couples every component to the exact shape of your state tree. <strong>Selectors</strong> decouple the &quot;what&quot; from the &quot;where.&quot;</p><pre>// user.selectors.ts<br>import { createFeatureSelector, createSelector } from &#39;@ngrx/store&#39;;<br>import { UserState } from &#39;./user.reducer&#39;;<br><br>export const selectUserState = createFeatureSelector&lt;UserState&gt;(&#39;users&#39;);<br><br>export const selectAllUsers = createSelector(<br>  selectUserState,<br>  (state) =&gt; state.users<br>);<br><br>export const selectUsersLoading = createSelector(<br>  selectUserState,<br>  (state) =&gt; state.loading<br>);<br><br>export const selectActiveUsers = createSelector(<br>  selectAllUsers,<br>  (users) =&gt; users.filter((u) =&gt; u.isActive)<br>);</pre><h3>Key Terms</h3><ul><li>createFeatureSelector — Grabs a top-level slice of state by its registered key.</li><li>createSelector — Composes one or more selectors into a derived value, and <strong>memoizes</strong> the result.</li><li><strong>Memoization</strong> — If the inputs haven’t changed, the selector returns the cached result instead of recomputing. This is why selectors are cheap to call from templates.</li></ul><h3>Using Selectors in a Component</h3><pre>// user-list.component.ts<br>export class UserListComponent {<br>  private store = inject(Store);<br><br>  users$ = this.store.select(selectAllUsers);<br>  loading$ = this.store.select(selectUsersLoading);<br><br>  ngOnInit() {<br>    this.store.dispatch(loadUsers());<br>  }<br>}</pre><pre>&lt;div *ngIf=&quot;loading$ | async&quot;&gt;Loading...&lt;/div&gt;<br>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let user of users$ | async&quot;&gt;{{ user.name }}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p><strong>Always use the </strong><strong>async pipe</strong> to subscribe to store selections in templates. It handles subscription and unsubscription for you — no manual .subscribe() and no memory leaks.</p><h3>3. Effects — Handling Side Effects</h3><h3>The Problem Reducers Can’t Solve</h3><p>Reducers must be pure — but real apps need to call APIs, read from localStorage, log analytics, and navigate routes. <strong>Effects</strong> are where that impure work lives, completely isolated from your state logic.</p><pre>// user.effects.ts<br>import { Injectable, inject } from &#39;@angular/core&#39;;<br>import { Actions, createEffect, ofType } from &#39;@ngrx/effects&#39;;<br>import { catchError, map, mergeMap, of } from &#39;rxjs&#39;;<br>import { UserService } from &#39;../services/user.service&#39;;<br>import { loadUsers, loadUsersSuccess, loadUsersFailure } from &#39;./user.actions&#39;;<br><br>@Injectable()<br>export class UserEffects {<br>  private actions$ = inject(Actions);<br>  private userService = inject(UserService);<br><br>  loadUsers$ = createEffect(() =&gt;<br>    this.actions$.pipe(<br>      ofType(loadUsers),<br>      mergeMap(() =&gt;<br>        this.userService.getUsers().pipe(<br>          map((users) =&gt; loadUsersSuccess({ users })),<br>          catchError((error) =&gt; of(loadUsersFailure({ error: error.message })))<br>        )<br>      )<br>    )<br>  );<br>}</pre><h3>The Effect Lifecycle</h3><pre>1. Component dispatches loadUsers()<br>2. Effect&#39;s actions$ stream picks it up via ofType(loadUsers)<br>3. mergeMap calls userService.getUsers() — the actual HTTP call<br>4. On success: maps the response into loadUsersSuccess({ users })<br>5. On failure: catchError intercepts and dispatches loadUsersFailure({ error })<br>6. The dispatched action flows back into the reducer<br>7. The reducer updates state, selectors emit, the UI re-renders</pre><p>Notice something important: <strong>the effect never touches state directly.</strong> It only listens for actions and dispatches new ones. This is the core discipline of NgRx — a strict, one-directional loop.</p><h3>mergeMap vs switchMap vs concatMap vs exhaustMap</h3><p>This is the single most common source of NgRx bugs. All four flatten an inner observable, but they behave very differently when the source action fires multiple times before the inner observable completes.</p><ul><li><strong>mergeMap</strong> — Runs all requests concurrently. Use for independent, unrelated calls (e.g., loading users, loading products — order and cancellation don’t matter).</li><li><strong>switchMap</strong> — Cancels the previous inner observable when a new action comes in. Use for search-as-you-type or “latest wins” scenarios.</li><li><strong>concatMap</strong> — Queues requests and runs them one at a time, in order. Use when order matters (e.g., a sequence of save operations).</li><li><strong>exhaustMap</strong> — Ignores new actions while one is already in flight. Use for things like a login button — you don’t want a double-submit to fire two requests.</li></ul><pre>// Login effect — exhaustMap prevents double-submission<br>login$ = createEffect(() =&gt;<br>  this.actions$.pipe(<br>    ofType(login),<br>    exhaustMap((action) =&gt;<br>      this.authService.login(action.credentials).pipe(<br>        map((user) =&gt; loginSuccess({ user })),<br>        catchError((error) =&gt; of(loginFailure({ error })))<br>      )<br>    )<br>  )<br>);</pre><p><strong>Common mistake:</strong> using switchMap for a &quot;save&quot; or &quot;delete&quot; action. If the user clicks save twice quickly, switchMap cancels the first save request mid-flight — silently dropping data. Use exhaustMap or concatMap for anything that mutates data.</p><h3>4. NgRx Entity — Managing Collections</h3><h3>Why Entity?</h3><p>Storing a list of items as a plain array (users: User[]) means every update, lookup, or removal requires looping through the array. <strong>@ngrx/entity</strong> normalizes your collection into a dictionary, making lookups O(1) instead of O(n).</p><pre>// user.reducer.ts (with Entity)<br>import { createEntityAdapter, EntityState } from &#39;@ngrx/entity&#39;;<br><br>export interface UserState extends EntityState&lt;User&gt; {<br>  loading: boolean;<br>  error: string | null;<br>}<br><br>export const userAdapter = createEntityAdapter&lt;User&gt;();<br><br>export const initialState: UserState = userAdapter.getInitialState({<br>  loading: false,<br>  error: null,<br>});<br><br>export const userReducer = createReducer(<br>  initialState,<br>  on(loadUsers, (state) =&gt; ({ ...state, loading: true })),<br>  on(loadUsersSuccess, (state, { users }) =&gt;<br>    userAdapter.setAll(users, { ...state, loading: false })<br>  ),<br>  on(deleteUserSuccess, (state, { id }) =&gt; userAdapter.removeOne(id, state))<br>);</pre><p><strong>Entity Adapter methods worth knowing:</strong></p><pre>adapter.addOne(entity, state);      // add a single entity<br>adapter.addMany(entities, state);   // add multiple<br>adapter.setAll(entities, state);    // replace the entire collection<br>adapter.updateOne(update, state);   // patch a single entity by id<br>adapter.removeOne(id, state);       // remove by id<br>adapter.upsertOne(entity, state);   // update if exists, add if not</pre><p>Entity also generates selectors for you:</p><pre>export const { selectAll, selectEntities, selectIds, selectTotal } = userAdapter.getSelectors();<br><br>export const selectAllUsers = createSelector(selectUserState, selectAll);</pre><h3>5. Testing NgRx</h3><h3>Testing Reducers</h3><p>Reducers are pure functions — the easiest thing in your entire app to test.</p><pre>describe(&#39;userReducer&#39;, () =&gt; {<br>  it(&#39;should set loading to true on loadUsers&#39;, () =&gt; {<br>    const state = userReducer(initialState, loadUsers());<br>    expect(state.loading).toBe(true);<br>  });<br><br>  it(&#39;should populate users on loadUsersSuccess&#39;, () =&gt; {<br>    const users = [{ id: 1, name: &#39;Alice&#39; }];<br>    const state = userReducer(initialState, loadUsersSuccess({ users }));<br>    expect(state.users).toEqual(users);<br>    expect(state.loading).toBe(false);<br>  });<br>});</pre><h3>Testing Selectors</h3><pre>describe(&#39;selectActiveUsers&#39;, () =&gt; {<br><br>  it(&#39;should return only active users&#39;, () =&gt; {<br>    const state = {<br>      users: {<br>        users: [<br>          { id: 1, name: &#39;Alice&#39;, isActive: true },<br>          { id: 2, name: &#39;Bob&#39;, isActive: false },<br>        ],<br>        loading: false,<br>        error: null,<br>      },<br>    };<br><br>    expect(selectActiveUsers.projector(state.users.users)).toEqual([<br>      { id: 1, name: &#39;Alice&#39;, isActive: true },<br>    ]);<br>  });<br><br>});</pre><h3>Testing Effects</h3><p>Effects need a mock Actions stream and a mocked service — this is where provideMockActions from @ngrx/effects/testing comes in.</p><pre>import { provideMockActions } from &#39;@ngrx/effects/testing&#39;;<br>import { Observable, of } from &#39;rxjs&#39;;<br><br>describe(&#39;UserEffects&#39;, () =&gt; {<br>  let actions$: Observable&lt;any&gt;;<br>  let effects: UserEffects;<br>  let userService: jasmine.SpyObj&lt;UserService&gt;;<br>  beforeEach(() =&gt; {<br>    userService = jasmine.createSpyObj(&#39;UserService&#39;, [&#39;getUsers&#39;]);<br>    TestBed.configureTestingModule({<br>      providers: [<br>        UserEffects,<br>        provideMockActions(() =&gt; actions$),<br>        { provide: UserService, useValue: userService },<br>      ],<br>    });<br>    effects = TestBed.inject(UserEffects);<br>  });<br><br>  it(&#39;should dispatch loadUsersSuccess on successful fetch&#39;, (done) =&gt; {<br>    const users = [{ id: 1, name: &#39;Alice&#39; }];<br>    userService.getUsers.and.returnValue(of(users));<br>    actions$ = of(loadUsers());<br>    effects.loadUsers$.subscribe((result) =&gt; {<br>      expect(result).toEqual(loadUsersSuccess({ users }));<br>      done();<br>    });<br>  });<br><br>});</pre><h3>6. The Facade Pattern — Keeping Components Clean</h3><h3>The Problem</h3><p>Injecting Store directly into every component and calling .select() and .dispatch() everywhere works, but it leaks NgRx implementation details into components that shouldn&#39;t care where state comes from.</p><h3>The Fix</h3><p>A <strong>Facade</strong> is a service that wraps all Store interaction for a feature, exposing a clean, component-friendly API.</p><pre>// user.facade.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserFacade {<br>  private store = inject(Store);<br><br>  users$ = this.store.select(selectAllUsers);<br>  <br>  loading$ = this.store.select(selectUsersLoading);<br>  <br>  loadUsers() {<br>    this.store.dispatch(loadUsers());<br>  }<br>  <br>  deleteUser(id: number) {<br>    this.store.dispatch(deleteUser({ id }));<br>  }<br>}</pre><pre>// user-list.component.ts<br>export class UserListComponent {<br>  private facade = inject(UserFacade);<br>  users$ = this.facade.users$;<br><br>  ngOnInit() {<br>    this.facade.loadUsers();<br>  }<br>}</pre><p>Now the component has no idea NgRx exists. If you ever swap state management libraries, only the facade changes — not every component that uses it.</p><h3>7. When NOT to Use NgRx</h3><p>This is the part most NgRx articles skip, and it’s arguably the most important section.</p><p>NgRx adds real overhead: boilerplate, a learning curve, and indirection. Not every piece of state deserves to live in a global store.</p><p><strong>Good candidates for the Store:</strong></p><ul><li>Data shared across many unrelated components (logged-in user, cart contents, feature flags)</li><li>Data that needs to survive navigation between routes</li><li>Complex state with many possible transitions that benefit from a strict, traceable history</li></ul><p><strong>Bad candidates for the Store:</strong></p><ul><li>A form’s local input state</li><li>A modal’s open/closed flag</li><li>Anything scoped to a single component that no sibling ever needs</li></ul><p><strong>The rule of thumb:</strong> if only one component (and its direct children) ever reads or writes a piece of state, it probably belongs in that component — as a plain property or a local signal() — not in NgRx.</p><h3>Wrapping Up</h3><p>NgRx isn’t complicated because Redux is complicated — it’s complicated because it forces discipline: one source of truth, pure reducers, isolated side effects, and a traceable action history. Once the pieces click — Actions describe <em>what happened</em>, Reducers decide <em>how state changes</em>, Selectors decide <em>what’s exposed</em>, and Effects handle <em>everything impure</em> — the pattern becomes predictable rather than mysterious.</p><p><strong>Your next step:</strong> Don’t try to convert an entire app to NgRx in one sitting. Pick one genuinely shared piece of state — something two or more unrelated components need — and move just that slice into the Store. Write the action, the reducer, the selector, and if it involves an API call, the effect. That’s your foundation.</p><h3>If you found this deep dive helpful, feel free to:</h3><ul><li><strong>Clap 👏</strong> if you learned something new about NgRx.</li><li><strong>Follow</strong> for more technical deep dives into Angular, Node.js, and clean code.</li><li><strong>Comment below:</strong> What part of NgRx has caused you the most pain — effects, entity, or knowing when <em>not</em> to use it? Or if you’ve got a pattern that saved your project, share it. Let’s discuss!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bfd62aa1c49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Skipping Angular Tests — Here’s Everything You Need]]></title>
            <link>https://medium.com/@bhaskarpaleti70366/stop-skipping-angular-tests-heres-everything-you-need-f5fc872e3020?source=rss-ef8d79a19685------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5fc872e3020</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Bhaskar]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 07:54:56 GMT</pubDate>
            <atom:updated>2026-03-29T08:13:52.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuFAoR036hounX6RmXbAzw.png" /></figure><blockquote>Master the art of writing reliable Angular tests — from setup to services — with clear explanations and real code examples.</blockquote><h3>Why Unit Testing Matters</h3><p>Before diving in, let’s answer the obvious question:</p><p>Unit testing is the practice of testing individual, isolated pieces of your application — a single component, a service method, a pipe — to verify they behave exactly as expected. When you write tests, you:</p><ul><li><strong>Catch bugs early</strong>, before they reach production</li><li><strong>Refactor confidently</strong>, knowing your tests will alert you if something breaks</li><li><strong>Document behavior</strong>, because a good test suite tells the story of what your code is supposed to do</li><li><strong>Impress interviewers</strong>, who increasingly treat testing as a first-class skill</li></ul><p>In Angular, the default testing stack is <strong>Karma</strong> (a test runner) + <strong>Jasmine</strong> (a testing framework). Understanding how they work together is essential for any Angular developer.</p><h3>1. Core Concepts &amp; Setup</h3><h3>What is Karma?</h3><p><strong>Karma</strong> is a test runner developed by the Angular team. It doesn’t write or run assertions — it launches a real browser (like Chrome), executes your test files inside it, and reports the results back to your terminal.</p><p>Think of Karma as the <em>stage manager</em> of your tests: it sets the scene, loads the actors, and tells you if the performance went well.</p><h3>What is Jasmine?</h3><p><strong>Jasmine</strong> is a behavior-driven testing framework. It provides the vocabulary you use to write your tests — functions like describe, it, expect, beforeEach, and matchers like toBe, toEqual, toHaveBeenCalled.</p><p>Think of Jasmine as the <em>language</em> you use to express what your code should do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7sSFn0rIoYtakXMc-jEjg.png" /></figure><h3>Project Setup</h3><p>When you create an Angular project with the CLI, Karma and Jasmine are already configured.</p><pre>ng new my-app   # Karma + Jasmine included by default<br>cd my-app<br>ng test         # Runs all *.spec.ts files</pre><p>Key configuration files:</p><ul><li>karma.conf.js — Karma&#39;s configuration (browser, reporters, coverage)</li><li>src/test.ts — Entry point that loads all spec files</li></ul><p>To generate a component <em>with</em> its spec file (default behavior):</p><pre>ng generate component user-profile<br># Creates: user-profile.component.ts<br>#          user-profile.component.spec.ts  ← your test file</pre><h3>The Anatomy of a Test File</h3><p>Every Jasmine test file follows this structure:</p><pre>// user-profile.component.spec.ts<br>describe(&#39;UserProfileComponent&#39;, () =&gt; { // 1. Test Suite<br>  <br>  beforeEach(() =&gt; {  // 2. Setup (runs before each test)<br>    // initialize stuff<br>  });<br>  it(&#39;should create the component&#39;, () =&gt; {  // 3. Individual Test (spec)<br>    expect(component).toBeTruthy();  // 4. Assertion<br>  });<br>  it(&#39;should display the user name&#39;, () =&gt; {<br>    expect(component.userName).toBe(&#39;Alice&#39;);<br>  });<br>  afterEach(() =&gt; {  // 5. Teardown (runs after each test)<br>    // clean up<br>  });<br>});</pre><p>Term What it means describe() Groups related tests into a suite it() Defines a single test (also called a &quot;spec&quot;) expect() Makes an assertion about a value beforeEach() Runs setup code before every it block afterEach() Runs cleanup code after every it block</p><h3>2. Component Testing</h3><h3>TestBed — Angular’s Testing Utility</h3><p><strong>TestBed</strong> is Angular&#39;s primary testing utility. It creates a mini Angular module specifically for testing, letting you declare components, provide services, and configure imports — just like @NgModule, but scoped to your test.</p><pre>import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;<br>import { UserProfileComponent } from &#39;./user-profile.component&#39;;<br><br>describe(&#39;UserProfileComponent&#39;, () =&gt; {<br>  let component: UserProfileComponent;<br>  let fixture: ComponentFixture&lt;UserProfileComponent&gt;;<br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>     declarations: [UserProfileComponent], // declare the component under test<br>     imports: [],     // any modules it needs<br>     providers: [],   // any services it needs<br>    }).compileComponents();<br>    fixture = TestBed.createComponent(UserProfileComponent);<br>    component = fixture.componentInstance;<br>    fixture.detectChanges(); // triggers ngOnInit and initial change detection<br>  });<br>  it(&#39;should create&#39;, () =&gt; {<br>    expect(component).toBeTruthy();<br>  });<br>});</pre><h3>Key Terms</h3><ul><li><strong>fixture</strong> — A wrapper around your component that gives you access to the component instance, the DOM, and change detection.</li><li><strong>fixture.componentInstance</strong> — The actual component class instance (your TypeScript class).</li><li><strong>fixture.nativeElement</strong> — The raw DOM element of the component.</li><li><strong>fixture.detectChanges()</strong> — Tells Angular to run change detection so the view updates to reflect the current state.</li></ul><h3>Testing Component Properties &amp; Methods</h3><pre>// counter.component.ts<br>@Component({ selector: &#39;app-counter&#39;, template: &#39;&lt;p&gt;{{ count }}&lt;/p&gt;&#39; })<br>export class CounterComponent {<br>  count = 0;<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><pre>// counter.component.spec.ts<br>it(&#39;should start with count of 0&#39;, () =&gt; {<br>  expect(component.count).toBe(0);<br>});<br><br>it(&#39;should increment count when increment() is called&#39;, () =&gt; {<br>  component.increment();<br>  expect(component.count).toBe(1);<br>});<br><br>it(&#39;should increment count multiple times&#39;, () =&gt; {<br>  component.increment();<br>  component.increment();<br>  component.increment();<br>  expect(component.count).toBe(3);<br>});</pre><h3>Testing the DOM (Template)</h3><p>Use fixture.nativeElement or the By utility to query the rendered HTML.</p><pre>import { By } from &#39;@angular/platform-browser&#39;;<br><br>it(&#39;should display the count in the template&#39;, () =&gt; {<br>  component.count = 5;<br>  fixture.detectChanges();  // sync the view<br>  const paragraph = fixture.nativeElement.querySelector(&#39;p&#39;);<br>  expect(paragraph.textContent).toContain(&#39;5&#39;);<br>});<br><br>it(&#39;should call increment() when button is clicked&#39;, () =&gt; {<br>  spyOn(component, &#39;increment&#39;);<br>  const button = fixture.debugElement.query(By.css(&#39;button&#39;));<br>  button.triggerEventHandler(&#39;click&#39;, null);<br>  expect(component.increment).toHaveBeenCalled();<br>});</pre><h3>Using Spies</h3><p>A <strong>spy</strong> is Jasmine’s way of watching and mocking function calls. It lets you verify that a function was called, how many times, and with what arguments — without actually running the real implementation.</p><pre>// Spy on a method and track calls<br>spyOn(component, &#39;increment&#39;);<br>component.increment();<br>expect(component.increment).toHaveBeenCalled();<br>expect(component.increment).toHaveBeenCalledTimes(1);<br><br>// Spy and replace the return value<br>spyOn(component, &#39;getUserName&#39;).and.returnValue(&#39;Alice&#39;);<br>expect(component.getUserName()).toBe(&#39;Alice&#39;);<br>// Spy and call through to the real implementation<br>spyOn(component, &#39;increment&#39;).and.callThrough();<br>component.increment();<br>expect(component.count).toBe(1);</pre><h3>Common Jasmine Matchers</h3><pre>expect(value).toBe(expected);           // strict equality (===)<br>expect(value).toEqual(expected);        // deep equality (objects/arrays)<br>expect(value).toBeTruthy();             // any truthy value<br>expect(value).toBeFalsy();              // any falsy value<br>expect(value).toBeNull();<br>expect(value).toBeUndefined();<br>expect(value).toContain(&#39;substring&#39;);   // string or array contains<br>expect(fn).toThrow();                   // function throws an error<br>expect(spy).toHaveBeenCalled();<br>expect(spy).toHaveBeenCalledWith(arg1, arg2);</pre><h4><strong>detectChanges() After Every State Change</strong></h4><p>One of the most common mistakes Angular developers make is changing a component property and immediately querying the DOM — without telling Angular to update the view first.</p><p>fixture.detectChanges() is not automatic in tests. You drive it manually. Every single time you mutate state, call it before making any DOM assertion.</p><p>typescript</p><pre>it(&#39;should show the updated username in the template&#39;, () =&gt; {<br>  component.username = &#39;Alice&#39;;<br>  fixture.detectChanges(); // ← without this, the DOM still shows the old value<br><br>  const el = fixture.nativeElement.querySelector(&#39;p&#39;);<br>  expect(el.textContent).toContain(&#39;Alice&#39;);<br>});</pre><p>The initial fixture.detectChanges() in beforeEach triggers ngOnInit and the first render. Any subsequent state change needs its own call. Think of it as the &quot;flush to screen&quot; button — nothing updates until you press it.</p><p><strong>NO_ERRORS_SCHEMA — Handling Child Components</strong></p><p>When you test a component that contains child components in its template, Angular will throw an error like:</p><p>&#39;app-user-card&#39; is not a known element</p><p>This happens because your TestBed module doesn&#39;t know about those child components. You have two options:</p><p><strong>Option 1 — Use </strong><strong>NO_ERRORS_SCHEMA (fast, shallow testing)</strong></p><pre>import { NO_ERRORS_SCHEMA } from &#39;@angular/core&#39;;<br><br>await TestBed.configureTestingModule({<br>  declarations: [UserListComponent], // only declare the component under test<br>  schemas: [NO_ERRORS_SCHEMA], // ignore unknown elements and attributes<br>}).compileComponents();</pre><p>NO_ERRORS_SCHEMA tells Angular to silently ignore any element or attribute it doesn&#39;t recognize. This is ideal for shallow tests where you only care about the parent component&#39;s logic, not its children.</p><p><strong>Option 2 — Declare the child component (deep testing)</strong></p><pre>await TestBed.configureTestingModule({<br>  declarations: [UserListComponent, UserCardComponent], // declare both<br>}).compileComponents();</pre><p>Use this when your test actually needs to assert something about the rendered output of the child component.</p><p><strong>The rule of thumb:</strong> use NO_ERRORS_SCHEMA by default in unit tests. Switch to declaring child components only when you specifically need to test the interaction between parent and child.</p><p><strong>BehaviorSubject Replay — The Gotcha Nobody Warns You About</strong></p><p>BehaviorSubject has one key behavior that trips up almost every developer the first time they write a test for it: <strong>it replays its current value to every new subscriber immediately on subscription.</strong></p><pre>it(&#39;should capture all emitted values including the initial one&#39;, () =&gt; {<br>  const subject = new BehaviorSubject&lt;string&gt;(&#39;Inactive&#39;);<br>  const emitted: string[] = [];<br>  subject.subscribe(val =&gt; emitted.push(val)); <br>  // immediately receives &#39;Inactive&#39;<br>  subject.next(&#39;Active&#39;);<br>  subject.next(&#39;Suspended&#39;);<br>  expect(emitted).toEqual([&#39;Inactive&#39;, &#39;Active&#39;, &#39;Suspended&#39;]);<br>  // NOT [&#39;Active&#39;, &#39;Suspended&#39;] — the initial value is always replayed<br>});</pre><p>This matters in component tests too. If your component subscribes to a BehaviorSubject in ngOnInit, it will immediately receive the current value — meaning your mock service must be initialized with a sensible default, not left empty.</p><pre>const mockUserService = {<br>  status$: new BehaviorSubject&lt;string&gt;(&#39;Inactive&#39;), // ← default matters<br>};</pre><p>If you only want to test values after a specific next() call and want to skip the initial replay, use skip(1):</p><pre>subject.pipe(skip(1)).subscribe(val =&gt; emitted.push(val));<br>subject.next(&#39;Active&#39;);<br>expect(emitted).toEqual([&#39;Active&#39;]); // initial value skipped</pre><p><strong>Spy Reset Between Tests</strong></p><p>When you create a jasmine.createSpyObj in beforeEach, the spy object itself is recreated fresh each time — so call counts don&#39;t leak between it blocks. However, if you reuse a spy across multiple interactions <em>within</em> the same test, the call count accumulates. And if you ever move spy setup outside beforeEach, you&#39;ll hit cross-test contamination.</p><p>The safe habit is to always reset explicitly when you need a clean slate mid-test:</p><pre>it(&#39;should only count calls from this interaction&#39;, () =&gt; {<br>  service.getFullName(&#39;John&#39;, &#39;Doe&#39;);<br>  expect(mockLoggerService.log).toHaveBeenCalledTimes(1);<br>  mockLoggerService.log.calls.reset(); // reset count and recorded calls<br>  service.getFullName(&#39;Jane&#39;, &#39;Smith&#39;);<br>  expect(mockLoggerService.log).toHaveBeenCalledTimes(1); // still 1, not 2<br>});</pre><p>Three reset methods worth knowing:</p><pre>spy.calls.reset();          // clears call history, spy stays active<br>spy.and.stub();             // removes any returnValue/callFake, resets to no-op<br>mockObj = jasmine.createSpyObj(&#39;Service&#39;, [&#39;log&#39;, &#39;warn&#39;]); // nuclear option — full rebuild</pre><blockquote>The calls.reset() approach is the most surgical. Use the full rebuild only when your spy has complex setup (.and.returnValue, .and.callFake) that you want completely wiped.</blockquote><p><strong>fakeAsync &amp; tick — Taking Control of Time</strong></p><p>Angular’s fakeAsync zone intercepts all asynchronous operations — setTimeout, setInterval, Promises, and RxJS delay/debounceTime operators — and puts them in a controlled queue. Nothing executes until you explicitly advance the clock with tick().</p><p><strong>Testing a debounced search input:</strong></p><p>typescript</p><pre>it(&#39;should debounce the search call by 300ms&#39;, fakeAsync(() =&gt; {<br>  const spy = spyOn(component, &#39;fetchResults&#39;);<br>  component.searchControl.setValue(&#39;angular&#39;);<br>  tick(299); // 299ms have passed — debounce hasn&#39;t fired yet<br>  expect(spy).not.toHaveBeenCalled();<br>  tick(1); // now at 300ms — debounce fires<br>  expect(spy).toHaveBeenCalledWith(&#39;angular&#39;);<br>}));</pre><p><strong>Testing a setTimeout:</strong></p><pre>it(&#39;should hide the banner after 2 seconds&#39;, fakeAsync(() =&gt; {<br>  component.showBanner = true;<br>  fixture.detectChanges();<br>  tick(2000); // fast-forward 2 seconds<br>  fixture.detectChanges();<br>  expect(component.showBanner).toBeFalse();<br>}));</pre><p><strong>Three time-control tools:</strong></p><pre>tick(500);          // advance clock by exactly 500ms<br>tick();             // advance by 0ms — flushes microtasks (Promises)<br>flush();            // drain all pending macrotasks regardless of time<br>discardPeriodicTasks(); // cancel any setInterval tasks still running</pre><blockquote>Common pitfallAlways call discardPeriodicTasks() or flush() at the end of a fakeAsync block if you have setInterval calls — otherwise Jasmine will throw &quot;1 timer(s) still in the queue.&quot;</blockquote><p><strong>fakeAsync vs </strong><strong>async/await:</strong> use async/await only for compileComponents() in beforeEach. For everything else — debounces, timeouts, delayed observables — use fakeAsync. Mixing them in the same it block causes unpredictable behavior.</p><h3>3. Service &amp; HTTP Testing</h3><h4>Testing a Simple Service</h4><p>For services without HTTP calls, you can often just instantiate them directly or use TestBed.inject.</p><pre>// calculator.service.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class CalculatorService {<br>  add(a: number, b: number): number {<br>    return a + b;<br>  }<br><br>  divide(a: number, b: number): number {<br>    if (b === 0) throw new Error(&#39;Cannot divide by zero&#39;);<br>    return a / b;<br>  }<br>}</pre><pre>// calculator.service.spec.ts<br>describe(&#39;CalculatorService&#39;, () =&gt; {<br>  let service: CalculatorService;<br><br>  beforeEach(() =&gt; {<br>    TestBed.configureTestingModule({});<br>    service = TestBed.inject(CalculatorService);<br>  });<br><br>  it(&#39;should be created&#39;, () =&gt; {<br>    expect(service).toBeTruthy();<br>  });<br><br>  it(&#39;should add two numbers correctly&#39;, () =&gt; {<br>    expect(service.add(2, 3)).toBe(5);<br>  });<br><br>  it(&#39;should throw when dividing by zero&#39;, () =&gt; {<br>    expect(() =&gt; service.divide(10, 0)).toThrowError(&#39;Cannot divide by zero&#39;);<br>  });<br>});</pre><h4>Testing Services with Dependencies</h4><p>When a service depends on another service, you <strong>mock</strong> the dependency to keep the test isolated. This is a critical concept in unit testing.</p><pre>// user.service.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  constructor(private loggerService: LoggerService) {}<br><br>  getFullName(first: string, last: string): string {<br>    const name = `${first} ${last}`;<br>    this.loggerService.log(`Got name: ${name}`);<br>    return name;<br>  }<br>}</pre><pre>// user.service.spec.ts<br>describe(&#39;UserService&#39;, () =&gt; {<br>  let service: UserService;<br>  let mockLoggerService: jasmine.SpyObj&lt;LoggerService&gt;;<br><br>  beforeEach(() =&gt; {<br>    // Create a spy object - a mock with spied methods<br>    mockLoggerService = jasmine.createSpyObj(&#39;LoggerService&#39;, [&#39;log&#39;]);<br>    TestBed.configureTestingModule({<br>      providers: [<br>        UserService,<br>        { provide: LoggerService, useValue: mockLoggerService }  // inject mock<br>      ]<br>    });<br>    service = TestBed.inject(UserService);<br>  });<br><br>  it(&#39;should return full name&#39;, () =&gt; {<br>    const result = service.getFullName(&#39;John&#39;, &#39;Doe&#39;);<br>    expect(result).toBe(&#39;John Doe&#39;);<br>  });<br><br>  it(&#39;should call loggerService.log with the name&#39;, () =&gt; {<br>    service.getFullName(&#39;John&#39;, &#39;Doe&#39;);<br>    expect(mockLoggerService.log).toHaveBeenCalledWith(&#39;Got name: John Doe&#39;);<br>  });<br>});</pre><blockquote><em>jasmine.createSpyObj. It creates an object where every listed method is automatically a spy — you never need to call </em><em>spyOn separately.</em></blockquote><h4>Testing HTTP Calls with HttpClientTestingModule</h4><p>For services that make HTTP requests, Angular provides HttpClientTestingModule and HttpTestingController — a powerful combo that lets you intercept HTTP requests and return fake responses, without ever hitting a real server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpLuB4qIxkJI-X3p9ucNzg.png" /></figure><pre>// data.service.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class DataService {<br>  constructor(private http: HttpClient) {<br><br>  getUsers(): Observable&lt;User[]&gt; {<br>    return this.http.get&lt;User[]&gt;(&#39;/api/users&#39;);<br>  }<br><br>  createUser(user: User): Observable&lt;User&gt; {<br>    return this.http.post&lt;User&gt;(&#39;/api/users&#39;, user);<br>  }<br>}</pre><pre>// data.service.spec.ts<br>import { HttpClientTestingModule, HttpTestingController } from &#39;@angular/common/http/testing&#39;;<br><br>describe(&#39;DataService&#39;, () =&gt; {<br>  let service: DataService;<br>  let httpMock: HttpTestingController;<br>  const mockUsers: User[] = [<br>    { id: 1, name: &#39;Alice&#39; },<br>    { id: 2, name: &#39;Bob&#39; }<br>  ];<br><br>  beforeEach(() =&gt; {<br>    TestBed.configureTestingModule({<br>     imports: [HttpClientTestingModule],// ← use this instead of HttpClientModule<br>     providers: [DataService]<br>    });<br>    service = TestBed.inject(DataService);<br>    httpMock = TestBed.inject(HttpTestingController);<br>  });<br><br>  afterEach(() =&gt; {<br>    httpMock.verify();  // ← ensures no unexpected HTTP calls were made<br>  });<br><br>  it(&#39;should fetch users via GET&#39;, () =&gt; {<br>    service.getUsers().subscribe(users =&gt; {<br>      expect(users.length).toBe(2);<br>      expect(users[0].name).toBe(&#39;Alice&#39;);<br>    });<br>    // Intercept the pending request and flush a fake response<br>    const req = httpMock.expectOne(&#39;/api/users&#39;);<br>    expect(req.request.method).toBe(&#39;GET&#39;);<br>    req.flush(mockUsers);  // ← provide the fake response data<br>  });<br><br>  it(&#39;should create a user via POST&#39;, () =&gt; {<br>    const newUser: User = { id: 3, name: &#39;Charlie&#39; };<br>    service.createUser(newUser).subscribe(user =&gt; {<br>      expect(user.name).toBe(&#39;Charlie&#39;);<br>    });<br>    const req = httpMock.expectOne(&#39;/api/users&#39;);<br>    expect(req.request.method).toBe(&#39;POST&#39;);<br>    expect(req.request.body).toEqual(newUser);<br>    req.flush(newUser);<br>  });<br><br>  it(&#39;should handle HTTP errors&#39;, () =&gt; {<br>    service.getUsers().subscribe({<br>      next: () =&gt; fail(&#39;Should have failed&#39;),<br>      error: (err) =&gt; {<br>        expect(err.status).toBe(500);<br>      }<br>    });<br>    const req = httpMock.expectOne(&#39;/api/users&#39;);<br>    req.flush(&#39;Server error&#39;, { status: 500, statusText: &#39;Internal Server Error&#39; });<br>  });<br>});</pre><p><strong>httpMock.verify() — What Actually Happens When It Fails</strong></p><p>You’ve seen httpMock.verify() called in afterEach, but what does it actually do when something goes wrong?</p><p>verify() throws an error if either of these conditions is true after a test:</p><ul><li>A request was made that you never called expectOne() on (unexpected request)</li><li>You called expectOne() but never flushed it (unfulfilled expectation)</li></ul><pre>afterEach(() =&gt; {<br>  httpMock.verify(); // throws if any request was left pending or unexpected<br>});<br><br>it(&#39;should catch an unexpected HTTP call&#39;, () =&gt; {<br>  // If your service secretly makes a second API call you didn&#39;t know about,<br>  // verify() will catch it and fail the test - protecting you from silent bugs<br>  service.getUsers().subscribe();<br><br>  httpMock.expectOne(&#39;/api/users&#39;).flush([]);<br>  // if getUsers() internally also calls &#39;/api/logger&#39;, verify() will throw here<br>});</pre><p>This makes verify() your safety net against silent over-fetching. If a refactor causes your service to make an extra HTTP call you didn&#39;t account for, verify() will catch it immediately rather than letting it slip into production.</p><h3>The HTTP Testing Flow</h3><pre>1. Call the service method (which internally calls this.http.get/post/etc.)<br>2. The request is held in a pending queue by HttpTestingController<br>3. Use httpMock.expectOne(url) to assert the request was made<br>4. Check request properties (method, headers, body)<br>5. Call req.flush(data) to simulate a server response<br>6. Your subscribe callback fires with the flushed data<br>7. afterEach: httpMock.verify() confirms no unexpected calls were left pending</pre><h4>Wrapping Up</h4><p>Unit testing in Angular is not just a checkbox on a job description — it’s a mindset. Once you understand the core trio of <strong>TestBed</strong>, <strong>Jasmine matchers</strong>, and <strong>HttpTestingController</strong>, you have everything you need to write meaningful tests for the vast majority of Angular code you’ll encounter.</p><p><strong>Your next step: <br></strong>Unit testing in Angular is a skill that pays compound interest. The first few tests feel slow and ceremonial. But once you internalize the TestBed setup, the fakeAsync/tick mental model, and the mock-first approach to services, you’ll write tests faster than you debug production issues.</p><p>Start small: pick the most complex component in your current project and write three tests for it — one for initial render, one for user interaction, one for a service dependency. That’s your foundation.</p><h3>If you found this deep dive helpful, feel free to:</h3><ul><li><strong>Clap 👏</strong> if you learned something new about Angular Unit Testing.</li><li><strong>Follow</strong> for more technical deep dives into Angular, Node.js, and clean code.</li><li><strong>Comment below:</strong> What part of Angular testing has caused you the most pain — async timing, mocking services, or something else entirely? Or if you’ve got a testing pattern that saved your project, share it. Let’s discuss!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5fc872e3020" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using any: Master TypeScript Generics for Safer, Smarter Code]]></title>
            <link>https://medium.com/@bhaskarpaleti70366/stop-using-any-master-typescript-generics-for-safer-smarter-code-6053a7ada0e8?source=rss-ef8d79a19685------2</link>
            <guid isPermaLink="false">https://medium.com/p/6053a7ada0e8</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Bhaskar]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 15:54:47 GMT</pubDate>
            <atom:updated>2026-03-20T09:22:48.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The “Any” Trap</h3><p>We’ve all been there. You’re racing against a deadline, hitting a complex API response, and the TypeScript compiler starts screaming at you. In a moment of frustration, you type those three letters: any.</p><p>Suddenly, the red squiggly lines vanish. The code compiles. Success? Not quite.</p><p>By using any, you’ve just told TypeScript to &quot;shut up and let me make mistakes.&quot; You lose IntelliSense, you lose refactoring safety, and most importantly, you lose the primary reason we use Angular in the first place: <strong>Type Safety.</strong></p><h3>Why Generics Matter in TypeScript</h3><p>TypeScript is all about adding type safety to JavaScript. But many beginners fall into the trap of using any everywhere. While any can make your code compile, it also removes all the benefits of TypeScript.</p><p>That’s where <strong>Generics</strong> come in. Generics let you write <strong>flexible, reusable, and type-safe code</strong> without losing information about the types you’re working with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPJ6ljvkor-uwDBMX0zYrg.png" /></figure><h4>1. The “First Element” Problem: Why We Need Generics</h4><p>The most common place developers encounter the need for generics is when a function’s return type depends on its input type. Imagine a utility that grabs the first item of an array.</p><p><strong>The “Any” Approach (Dangerous):</strong> If you use any, you lose the connection between the input and the output.</p><pre>function getFirstElement(array: any[]): any {<br>  return array[0];<br>}<br><br>const numbers = [1, 2, 3];<br>const first = getFirstElement(numbers);<br><br>// TypeScript thinks &#39;first&#39; is &#39;any&#39;, so this won&#39;t error:<br>first.toUpperCase(); // Runtime crash! Numbers don&#39;t have toUpperCase</pre><pre>function getFirstElement&lt;T&gt;(array: T[]): T {<br>  return array[0];<br>}<br><br>const numbers = [1, 2, 3];<br>const firstNumber = getFirstElement(numbers); // TypeScript infers T = number ✅<br><br>const strings = [&#39;Angular&#39;, &#39;TypeScript&#39;, &#39;React&#39;];<br>const firstString = getFirstElement(strings); // TypeScript infers T = string ✅<br><br>// Now TypeScript WILL catch this:<br>firstNumber.toUpperCase(); // Error: Property &#39;toUpperCase&#39; does not exist on type &#39;number&#39; ✅</pre><h4>2. Standardizing API Responses with Generic Types</h4><p>In a production Angular app, you’ll likely deal with dozens of different API endpoints. Instead of creating a unique interface for every single response, you can create one <strong>Generic API Response</strong> type.</p><p>This allows you to keep consistent metadata (like isError or status) while swapping out the specific data payload.</p><pre>// The &quot;copy-paste&quot; approach — don&#39;t do this<br>interface UserApiResponse {<br>  data: User;<br>  isError: boolean;<br>  statusCode: number;<br>}<br><br>interface BlogApiResponse {<br>  data: BlogPost;<br>  isError: boolean;<br>  statusCode: number;<br>}<br><br>// ...repeat 50 times for every endpoint<br></pre><p>With a generic ApiResponse&lt;T&gt;, you define the wrapper shape once:</p><pre>interface ApiResponse&lt;TData&gt; {<br>  data: TData;<br>  isError: boolean;<br>  statusCode: number;<br>  message: string;<br>}<br><br>// Create specific response types by &quot;filling in&quot; the generic<br>type UserResponse = ApiResponse&lt;User&gt;;<br>type BlogResponse = ApiResponse&lt;BlogPost&gt;;<br>type PaginatedUsersResponse = ApiResponse&lt;User[]&gt;;</pre><p>Now your Angular service becomes clean and fully type-safe:</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  constructor(private http: HttpClient) {}<br><br>  getUser(id: string): Observable&lt;ApiResponse&lt;User&gt;&gt; {<br>    return this.http.get&lt;ApiResponse&lt;User&gt;&gt;(`/api/users/${id}`);<br>  }<br><br>  getUsers(): Observable&lt;ApiResponse&lt;User[]&gt;&gt; {<br>    return this.http.get&lt;ApiResponse&lt;User[]&gt;&gt;(&#39;/api/users&#39;);<br>  }<br>}</pre><h4>3. Advanced: Constraints and Default Values</h4><p>Sometimes you want your generics to be flexible, but not <em>too</em> flexible. You can use the extends keyword to force a generic to adhere to a specific shape—for example, ensuring the data is always an object.</p><p>You can also provide a <strong>default type</strong> so that the user doesn’t always have to manually specify it.</p><pre>// Without constraints — too permissive<br>function printId&lt;T&gt;(item: T): void {<br>  console.log(item.id); // ❌ Error: Property &#39;id&#39; does not exist on type &#39;T&#39;<br>}<br><br>// With a constraint — just right<br>interface HasId {<br>  id: string | number;<br>}<br><br>function printId&lt;T extends HasId&gt;(item: T): void {<br>  console.log(item.id); // ✅ TypeScript knows T will always have &#39;id&#39;<br>}<br><br>printId({ id: &#39;123&#39;, name: &#39;Bhaskar&#39; }); // ✅ Works — has an &#39;id&#39;<br>printId({ name: &#39;Bhaskar&#39; });            // ❌ Error: missing &#39;id&#39; propertyUsing constraints (extends) and defaults (=) is the &quot;Gold Standard&quot; for building libraries or complex Angular services where you want to provide a great developer experience</pre><h4>4: keyof — The Key to Dynamic Type Safety</h4><p>This is where generics get genuinely powerful. The keyof operator extracts a union type of all the keys of a given type.</p><pre>interface User {<br>  id: string;<br>  name: string;<br>  email: string;<br>  age: number;<br>}<br><br>type UserKeys = keyof User; // &quot;id&quot; | &quot;name&quot; | &quot;email&quot; | &quot;age&quot;</pre><p>Combined with generics, keyof lets you write functions that are dynamic but still fully type-checked:</p><pre>// This function works on ANY object, picking ANY valid key — type-safely<br>function getProperty&lt;T, K extends keyof T&gt;(obj: T, key: K): T[K] {<br>  return obj[key];<br>}<br><br>const user: User = { id: &#39;1&#39;, name: &#39;Bhaskar&#39;, email: &#39;b@example.com&#39;, age: 28 };<br><br>const name = getProperty(user, &#39;name&#39;);   // TypeScript knows this is &#39;string&#39; ✅<br>const age  = getProperty(user, &#39;age&#39;);    // TypeScript knows this is &#39;number&#39; ✅<br><br>getProperty(user, &#39;password&#39;);            // ❌ Error: &quot;password&quot; is not a key of User</pre><h4>5: Built-in Utility Types (TypeScript’s Generic Toolkit)</h4><p>TypeScript ships with a library of built-in generic types that solve extremely common problems. These are used constantly in production codebases and are worth knowing well.</p><h4>Partial&lt;T&gt; — All properties become optional</h4><p>Perfect for update/patch operations where you only want to change some fields:</p><pre>interface User {<br>  id: string;<br>  name: string;<br>  email: string;<br>  role: &#39;admin&#39; | &#39;user&#39;;<br>}<br><br>// Partial&lt;User&gt; = { id?: string; name?: string; email?: string; role?: ... }<br>function updateUser(id: string, changes: Partial&lt;User&gt;): Observable&lt;User&gt; {<br>  return this.http.patch&lt;User&gt;(`/api/users/${id}`, changes);<br>}<br><br>// Now callers can pass only the fields they want to change<br>updateUser(&#39;123&#39;, { name: &#39;New Name&#39; });           // ✅ Only updating name<br>updateUser(&#39;123&#39;, { role: &#39;admin&#39;, email: &#39;...&#39; }); // ✅ Updating two fields</pre><h4>Pick&lt;T, K&gt; — Select only the fields you need</h4><pre>// You don&#39;t always want to expose the full User in the UI<br>type UserPreview = Pick&lt;User, &#39;id&#39; | &#39;name&#39;&gt;;<br>// Result: { id: string; name: string }<br><br>// Useful for lightweight components that only need minimal data<br>@Component({ ... })<br>export class UserAvatarComponent {<br>  @Input() user!: UserPreview; // Only needs id and name — nothing else leaks in<br>}</pre><h4>Omit&lt;T, K&gt; — Everything except certain fields</h4><p>The inverse of Pick — great for &quot;create&quot; operations where the server generates certain fields:</p><pre>// When creating a user, the server generates id and createdAt<br>type CreateUserPayload = Omit&lt;User, &#39;id&#39; | &#39;createdAt&#39;&gt;;<br>// Result: { name: string; email: string; role: &#39;admin&#39; | &#39;user&#39; }<br><br>function createUser(payload: CreateUserPayload): Observable&lt;User&gt; {<br>  return this.http.post&lt;User&gt;(&#39;/api/users&#39;, payload);<br>}</pre><h4>Record&lt;K, V&gt; — Build typed dictionaries</h4><pre>// A cache keyed by user ID<br>const userCache: Record&lt;string, User&gt; = {};<br><br>// A permissions map for specific roles<br>type Role = &#39;admin&#39; | &#39;editor&#39; | &#39;viewer&#39;;<br>const permissions: Record&lt;Role, string[]&gt; = {<br>  admin:  [&#39;read&#39;, &#39;write&#39;, &#39;delete&#39;],<br>  editor: [&#39;read&#39;, &#39;write&#39;],<br>  viewer: [&#39;read&#39;],<br>};</pre><h4>Part 6: Conditional Types — Generics That Think</h4><p>Conditional types let your type system make decisions based on what type it receives. The syntax reads like a ternary operator:</p><pre>type IsString&lt;T&gt; = T extends string ? &#39;yes&#39; : &#39;no&#39;;<br><br>type A = IsString&lt;string&gt;;  // &quot;yes&quot;<br>type B = IsString&lt;number&gt;;  // &quot;no&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*PcnmuNpPKzgEvHELpP5iQw.png" /><figcaption>From — Stop using `any`: master TypeScript generics · by Bhaskar</figcaption></figure><h4>Conclusion: Making Your Code Predictable</h4><p>Mastering Generics is one of the most significant steps you can take in your journey from a junior to a senior developer. While using any might save you five seconds today, it often costs you hours of debugging next month.</p><p>By using Generics, you aren’t just writing code that works — you’re writing code that <strong>communicates</strong>. You’re telling other developers (and your future self) exactly what kind of data to expect, while keeping your logic flexible enough to handle any scenario.</p><p><strong>Your next step:</strong> Look at your current Angular project. Find one service or component that uses any and try to refactor it using a Generic. You’ll be surprised at how much more confident you feel when those red squiggly lines are gone for the <em>right</em> reasons.</p><h4>If you found this deep dive helpful, feel free to:</h4><ul><li><strong>Clap 👏</strong> if you learned something new about TypeScript Generics!</li><li><strong>Follow</strong> for more technical deep dives into Angular, Node.js, and clean code.</li><li><strong>Comment below:</strong> What is the most complex “any” type you’ve had to refactor into a Generic? Or are you still facing issues with complex nested types? Let’s discuss!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6053a7ada0e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Angular Change Detection: How Zone.js and NgZone Really Work]]></title>
            <link>https://javascript.plainenglish.io/understanding-angular-change-detection-how-zone-js-and-ngzone-really-work-70625b10f1ea?source=rss-ef8d79a19685------2</link>
            <guid isPermaLink="false">https://medium.com/p/70625b10f1ea</guid>
            <category><![CDATA[ngzone]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-change-detection]]></category>
            <category><![CDATA[change-detection-strategy]]></category>
            <category><![CDATA[zonejs-in-angular]]></category>
            <dc:creator><![CDATA[Bhaskar]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 16:01:49 GMT</pubDate>
            <atom:updated>2026-03-19T07:28:52.218Z</atom:updated>
            <content:encoded><![CDATA[<p>Change detection is one of the most important — and most misunderstood — concepts in Angular.<br>As developers, we often take UI updates for granted. We change a variable, and magically the view updates.</p><blockquote>Behind the scenes, Angular relies heavily on Zone.js to track asynchronous operations like (click, mouse events, timers, promises) and it notifies angular that something might have changed.</blockquote><p>But what is it, really? And how does Zone.js make it all possible?</p><h4>1. What is Change Detection?</h4><p>Angular change detection is a process that keeps the UI (the template) in sync with your data model (your component class). When the state of your application changes, Angular needs to reflect those changes in the view. This process of checking the component’s data and updating the rendered HTML is called change detection.</p><p>Think of it like this: You have a variable message in your component. In your template, you display it with {{message}}. When you update message from &quot;Hello&quot; to &quot;Goodbye&quot;, you expect the screen to change instantly. Angular&#39;s change detection is the mechanism that makes that happen.</p><h4>The Unsung Hero: Zone.js</h4><p>How does Angular know <em>when</em> to run change detection? It doesn’t read your mind. It needs a trigger. This is where Zone.js comes in.</p><p>Zone.js is a library that monkey-patches almost all browser asynchronous APIs. It essentially wraps functions like setTimeout, addEventListener (for events like click), and Promise.then so that it can execute code <em>before</em> and <em>after</em> they run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*OEtct0qqjrdiOh2J" /></figure><p>Think of Zone.js as an execution context that can intercept asynchronous tasks. Angular creates its own zone called NgZone. When an asynchronous operation finishes, Zone.js notifies NgZone, and NgZone then tells Angular, &quot;Hey, something asynchronous just happened. You should probably run change detection now just in case.&quot;</p><blockquote>What is Monkey Patching?<br>Monkey patching is a way to modify or extend the behavior of existing functions at runtime by replacing them with custom implementations. In Zone.js, it wraps browser APIs to detect when asynchronous operations start and finish, then notifies Angular.</blockquote><h4>A Simplified Look at Zone.js Internals</h4><p>To understand how Angular knows when a setTimeout or a click finishes, let&#39;s look at a simplified version of how Zone.js is actually structured. It essentially acts as a wrapper that surrounds your code with &quot;start&quot; and &quot;end&quot; signals.</p><h4>1. The Zone Execution Context</h4><p>Think of the Zone class as a manager. It ensures that whenever your code runs, it knows exactly when it enters and when it leaves.</p><pre>// A simplified version of how Zone.js tracks your code<br>class MyZone {<br>  run(fn) {<br>    this.onEnter(); // Signal: &quot;Code is starting!&quot;<br>    try {<br>      fn(); // Execute your actual logic<br>    } finally {<br>      this.onExit(); // Signal: &quot;Code is done!&quot;<br>    }<br>  }<br><br>  onEnter() {<br>    console.log(&#39;--- Entering Zone ---&#39;);<br>  }<br><br>  onExit() {<br>    console.log(&#39;--- Exiting Zone ---&#39;);<br>    // CRITICAL: This is where NgZone tells Angular: <br>    // &quot;Everyone is done working, now update the UI!&quot;<br>    this.triggerAngularChangeDetection();<br>  }<br><br>  triggerAngularChangeDetection() {<br>    console.log(&#39;Angular is now checking the component tree for updates...&#39;);<br>  }<br>}</pre><p>Now, how does your code end up inside that run() method? Zone.js monkey patches the browser&#39;s native functions so that they automatically use the Zone.</p><pre>// Step 1: Save the original browser function<br>const originalSetTimeout = window.setTimeout;<br><br>// Step 2: Replace it with our &quot;Zone-aware&quot; version<br>window.setTimeout = (callback, delay) =&gt; {<br>  const zone = new MyZone(); // In reality, this uses the existing NgZone<br>  <br>  // Step 3: Wrap the user&#39;s callback so it runs INSIDE the zone<br>  const wrappedCallback = () =&gt; {<br>    zone.run(callback); <br>  };<br>  <br>  // Step 4: Call the real browser timer with our wrapped version<br>  return originalSetTimeout(wrappedCallback, delay);<br>};</pre><h4>2. The Performance Trap: The “Zone Leak”</h4><p>The problem? Zone.js is <strong>over-eager</strong>. Because it wraps <em>every</em> event, Imagine you are integrating a heavy charting library like <strong>D3.js</strong> or <strong>Google Maps</strong>. These libraries have their own internal animation loops. If you initialize them normally, every internal tick of the map or chart will force Angular to re-check your entire component tree.</p><p><strong>how do we fix this issue ?</strong><strong>runOutsideAngular()</strong> To prevent this, we &quot;step out&quot; of the Zone. This tells Angular: &quot;I&#39;m doing work here, but don&#39;t worry about updating the UI until I say so.&quot;</p><pre>import { Component, NgZone, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-heavy-logic&#39;,<br>  template: `<br>    &lt;p&gt;Progress: {{ progress }}%&lt;/p&gt;<br>    &lt;button (click)=&quot;processData()&quot;&gt;Start Heavy Task&lt;/button&gt;<br>  `<br>})<br>import { Component, NgZone, ElementRef, AfterViewInit } from &#39;@angular/core&#39;;<br><br>@Component({ ... })<br>export class AnalyticsComponent implements AfterViewInit {<br>  constructor(private ngZone: NgZone, private el: ElementRef) {}<br><br>  ngAfterViewInit() {<br>    // We run this OUTSIDE the zone to prevent every mouse-hover <br>    // on the chart from triggering Angular Change Detection.<br>    this.ngZone.runOutsideAngular(() =&gt; {<br>      const chart = new HeavyChartLibrary(this.el.nativeElement);<br>      chart.init();<br><br>      chart.on(&#39;dataUpdate&#39;, (newData) =&gt; {<br>         // Only jump back INSIDE the zone when we actually need to update an @Input<br>         if (newData.isCritical) {<br>           this.ngZone.run(() =&gt; {<br>             this.progress = newData.value; <br>           });<br>         }<br>      });<br>    });<br>  }<br>}</pre><blockquote>Why this works: When you use runOutsideAngular, the onExit() method in our simplified MyZone class is never triggered for those specific internal operations. Angular remains &quot;blind&quot; to those changes until you explicitly jump back in using this.ngZone.run().</blockquote><h4>5. Controlling the Flow: Default vs. OnPush</h4><p>Now that we know how Angular is notified, we need to talk about how it actually performs the check. Angular gives us two strategies to manage this: Default and OnPush.</p><h4>The Default Strategy:</h4><p>Check Everything By default, Angular uses the CheckAlways strategy. Whenever a change is detected (anywhere in the app!), Angular starts from the top root component and checks every single component in the tree, from top to bottom. The Good: It’s “magic.” You change a variable, and it just works. The Bad: In a large app with 500 components, checking 500 components because you clicked a single button is a huge waste of CPU.</p><h4>The OnPush Strategy:</h4><p>When you switch a component to ChangeDetectionStrategy.OnPush, you are telling Angular: “Stop being so aggressive. Only check me if I absolutely need it.” <br>A component with OnPush only re-renders in three specific cases:</p><p>a) An @Input() reference changes.</p><pre><br>export class ParentComponent{<br>  user: User;<br>  onClick() {<br>      // Reference remains the same. UI won&#39;t update.<br>      this.user.name = &#39;Bhaskar&#39;; <br>      // ✅ Immutability (The Spread Operator)<br>      this.user = { ...this.user, name: &#39;Bhaskar&#39; };<br>  }<br>}<br><br><br>@Component({<br>  selector: &#39;child-component&#39;,<br>  template: `<br>    &lt;h2&gt;Demo: NgZone&lt;/h2&gt;<br><br>    &lt;p&gt;{{user.name}}&lt;/p&gt;<br><br>  `,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>})<br>export class ChildComponent {<br>  @Input() user: any;<br><br>  ngOnInit() {}<br>}</pre><p>b) An Event handler (like (click)) inside the component is triggered.</p><pre>@Component({<br>  selector: &#39;child-component&#39;,<br>  template: `<br>    &lt;h2&gt;Demo: NgZone&lt;/h2&gt;<br><br>    &lt;p&gt;{{user.name}}&lt;/p&gt;<br><br>  `,<br>// We are telling Angular: &quot;Don&#39;t check me unless an @Input changes or an event fires.&quot;<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>})<br>export class ChildComponent {<br>  @Input() user: any;<br><br>  updateName() {<br>    // No manual &#39;markForCheck&#39; needed! <br>    // The (click) handler automatically triggers change detection for this component.<br>    this.user.name = &#39;Bhaskar&#39;<br>  }<br>}</pre><p>c) You manually trigger it (using ChangeDetectorRef).</p><pre>import { ChangeDetectorRef, Component, ChangeDetectionStrategy, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-price-ticker&#39;,<br>  template: `&lt;h1&gt;Current Price: {{ price }}&lt;/h1&gt;`,<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class ChildComponent implements OnInit {<br>  user:User;<br>  constructor(private cdr: ChangeDetectorRef) {}<br><br>  ngOnInit() {<br>    // Webhooks/Sockets run outside the &quot;Template Event&quot; scope<br>    this.userService.getUser((user) =&gt; {<br>      this.user= user;<br><br>      // We tell Angular: &quot;I know nothing changed in the inputs, <br>      // but trust me, you need to check this component.&quot;<br>      this.cdr.markForCheck(); <br>    });<br>  }<br>}</pre><h4>The “Gold Standard”: OnPush + RxJS | async</h4><p>In a professional environment, we rarely handle manual subscriptions. The AsyncPipe is your best friend because it automatically calls markForCheck() whenever a new value is emitted.</p><p>TypeScript</p><pre>@Component({<br>  selector: &#39;app-user-profile&#39;,<br>  template: `<br>    &lt;div *ngIf=&quot;user$ | async as user&quot;&gt;<br>      {{ user.name }}<br>    &lt;/div&gt;<br>  `,<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class UserProfileComponent {<br>  user$ = this.userService.userStream$; // Pure RxJS data flow<br>}</pre><h4>Why this is the “Gold Standard”</h4><ul><li><strong>No Memory Leaks:</strong> It automatically calls .unsubscribe() when the component is destroyed.</li><li><strong>No Manual CDR:</strong> You don’t have to sprinkle this.cdr.markForCheck() all over your TypeScript files.</li><li><strong>Cleaner Code:</strong> Your TypeScript file focuses on <strong>Logic</strong>, and your HTML focuses on <strong>Presentation</strong>.</li><li><strong>Performance:</strong> It perfectly satisfies the OnPush requirement by only triggering a check when new data actually exists.</li></ul><p><strong>6.</strong> <strong>TheDeveloper’sNightmare</strong>:ExpressionChangedAfterItHasBeenCheckedError</p><p>If you’ve worked with Angular for any length of time, you’ve seen this error in the console. It usually happens when a value in your component changes <strong>after</strong> Angular has already finished checking it for the current render cycle.</p><pre>@Component({<br>  selector: &#39;child-component&#39;,<br>  template: `<br>    &lt;h2&gt;Demo: NgZone&lt;/h2&gt;<br><br>    &lt;p&gt;{{user.name}}&lt;/p&gt;<br><br>  `,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>})<br>export class ChildComponent {<br>  @Input() user: User;<br><br>  ngAfterViewInit() {<br>    this.user.name = &#39;Bhaskar&#39;<br>  }<br>}</pre><h4>Conclusion: Mastering the Flow</h4><p>Change detection is the boundary where your data meets the DOM. As we’ve explored, the journey from a simple variable change to a rendered pixel involves a sophisticated dance between <strong>Zone.js</strong> and <strong>Angular’s checking engine</strong>.</p><p>By moving from the “magic” of the Default strategy to the intentionality of <strong>OnPush</strong> and <strong>RxJS</strong>, you aren’t just making your app faster — you are making your state management predictable and professional.</p><h4>🚀 The Future: Towards a “Zoneless” Angular</h4><p>While understanding Zone.js is critical today, the Angular landscape is shifting. With the introduction of <strong>Angular Signals</strong> (v16+), we are entering an era of <strong>fine-grained reactivity</strong>.</p><p>Signals allow Angular to know exactly which part of the DOM needs to change without relying on Zone.js to monkey-patch the browser. As you grow in your Angular journey, keep an eye on “Zoneless” applications — they are the next evolution in high-performance web development.</p><h3><strong>If you found this deep dive helpful, feel free to:</strong></h3><ul><li><strong>Clap</strong> 👏 if you learned something new about NgZone!</li><li><strong>Follow</strong> for more technical deep dives into Angular and Node.js.</li><li><strong>Comment</strong> below: What is the weirdest ExpressionChangedAfterItHasBeenCheckedError you&#39;ve ever had to debug?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70625b10f1ea" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-angular-change-detection-how-zone-js-and-ngzone-really-work-70625b10f1ea">Understanding Angular Change Detection: How Zone.js and NgZone Really Work</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing REST APIs That Your Frontend Can Actually Trust]]></title>
            <link>https://javascript.plainenglish.io/designing-rest-apis-that-your-frontend-can-actually-trust-b0dd4306300c?source=rss-ef8d79a19685------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0dd4306300c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Bhaskar]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 16:09:10 GMT</pubDate>
            <atom:updated>2026-03-19T07:42:16.282Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Full-Stack Developer’s Guide to Building Production-Ready Node.js APIs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOd3n5pklg9dTxxoeV7T9Q.jpeg" /><figcaption>By Bhaskar, Senior Full-Stack Developer (Angular/React.js/Node.js)</figcaption></figure><h4>Introduction: Beyond “It Works”</h4><p>After four years building full-stack applications with Angular and Node.js, I’ve learned a hard truth: your API is a product, and your frontend developers are your customers.</p><p>I’ve been on both sides of the fence. I’ve built Node.js APIs that made Angular developers curse my name, and I’ve consumed badly designed APIs that turned simple features into debugging nightmares. This article is everything I wish I’d known when I started — a practical guide to building Node.js REST APIs that frontend teams can actually trust.</p><p>We’ll build our understanding around a real example: a Chat Application API. Each principle will include why it matters, how to implement it in Node.js, and what it looks like from Angular’s perspective.</p><blockquote>1. Resources over Actions (Nouns, not Verbs)</blockquote><p>In the phase of development, we tend to think in terms of <strong>actions</strong>. Early in my career, I wrote endpoints like this: /getUser, <em>/deleteUser, </em>/updateUser, /createUser We are essentially putting the &quot;verb&quot; inside the URL. But in a professional REST API, the URL should only ever be a <strong>noun</strong>.</p><pre>// DON&#39;T DO THIS - Action-based endpoints<br>app.post(&#39;/getUser&#39;, messageController.create);<br>app.get(&#39;/deleteUser&#39;, messageController.getAll);<br>app.post(&#39;/updateUser/:id&#39;, messageController.delete);<br>app.post(&#39;/createUser/:id&#39;, messageController.markRead);</pre><p><em>This feels natural because we think in actions. But it creates chaos:</em></p><ul><li><em>Your API grows exponentially with every new feature</em></li><li><em>Frontend code becomes bloated with custom methods</em></li><li><em>HTTP verbs lose their meaning (POST does everything)</em></li></ul><pre>// DO THIS - Resource-based endpoints<br>// routes/message.routes.js<br>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const userController = require(&#39;./user.controller&#39;);<br><br>router.get(&#39;/&#39;, userController.getUsers);        // GET /api/users<br>router.get(&#39;/:id&#39;, userController.getUserById);  // GET /api/user/123<br>router.post(&#39;/&#39;, userController.createUser);     // POST /api/user<br>router.patch(&#39;/:id&#39;, userController.updateUser); // PATCH /api/user/123<br>router.delete(&#39;/:id&#39;, userController.deleteUser);// DELETE /api/user/123<br><br>module.exports = router;</pre><blockquote>Resource-Based URLs (RESTful Approach)</blockquote><p><strong>Description:</strong> This contemporary and preferred style, which adheres to Representational State Transfer (REST) principles, treats URLs as names for <em>resources</em> (nouns). The operation to be performed on that resource is determined solely by the standard HTTP method used.</p><pre>HTTP Method | Operation      | Resource URL | Explanation<br>------------|----------------|--------------|---------------------------<br>GET         | Read           | /users       | Retrieve a list of users.<br>GET         | Read           | /users/5     | Retrieve specific user.<br>POST        | Create         | /users       | Create a new user.<br>PUT         | Update/Replace | /users/5     | Fully replace user 5.<br>PATCH       | Update/Modify  | /users/5     | Partially update user 5.<br>DELETE      | Delete         | /users/5     | Remove user 5.</pre><blockquote><strong>The Professional Way :</strong>when every your declaring api endpoint just write the resource name (noun) let the http method take care of the action (verb)</blockquote><blockquote>2. Respecting the HTTP Contract (Status Codes)</blockquote><p>In API design, <strong>HTTP Status Codes</strong> are those immediate verbal cues. They are not just “extra info” — they are the core of the contract between the backend and the frontend.</p><h4>The “Everything is 200 OK” Mistake</h4><p>The most common sign of an unprofessional API is returning 200 OK for every single request, even when something goes wrong. Developers then hide the real status inside the JSON body:</p><p><strong>(Don’t do this):</strong></p><pre>// HTTP Status: 200 OK (Confusing!)<br>{<br>  &quot;status&quot;: &quot;error&quot;,<br>  &quot;message&quot;: &quot;User not found&quot;<br>}</pre><p>This is a nightmare for frontend developers. It forces us to write extra logic to “peek” inside every single response just to see if it actually succeeded</p><pre>// Angular has to implement custom error handling for EVERY request<br>this.http.get(&#39;/api/users/123&#39;).subscribe({<br>  next: (response: any) =&gt; {<br>    if (response.status === &#39;error&#39;) {<br>      // Manually handle error even though HTTP succeeded!<br>      this.showError(response.message);<br>      return;<br>    }<br>    // Handle success<br>    this.user = response.data;<br>  },<br>  error: (err) =&gt; {<br>    // This never gets called because HTTP status was 200! 😱<br>  }<br>});</pre><h4>The Professional Way (Standard Status Codes)</h4><p>A professional API uses the built-in language of the internet. By using the correct status code, the frontend knows exactly what happened before even reading a single line of your JSON.</p><pre>// GOOD: Let HTTP status codes do their job<br>// message.controller.js<br>exports.getMessageById = async (req, res, next) =&gt; {<br>  try {<br>    const message = await Message.findById(req.params.id);<br>    <br>    if (!message) {<br>      return res.status(404).json({<br>        error: {<br>          code: &#39;MESSAGE_NOT_FOUND&#39;,<br>          message: `Message with ID ${req.params.id} does not exist`<br>        }<br>      });<br>    }<br>    <br>    res.status(200).json({<br>      data: message<br>    });<br>  } catch (error) {<br>    next(error); // Pass to error handling middleware<br>  }<br>};</pre><p>Now frontend can use interceptors for global error handling:</p><pre>// Angular Interceptor<br>@Injectable()<br>export class ErrorInterceptor implements HttpInterceptor {<br>  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    return next.handle(req).pipe(<br>      catchError((error: HttpErrorResponse) =&gt; {<br>        let errorMessage = &#39;An unknown error occurred&#39;;<br>        <br>        if (error.status === 404) {<br>          errorMessage = &#39;Resource not found&#39;;<br>        } else if (error.status === 401) {<br>          errorMessage = &#39;Please log in again&#39;;<br>          this.router.navigate([&#39;/login&#39;]);<br>        } else if (error.status === 403) {<br>          errorMessage = &#39;You don\&#39;t have permission&#39;;<br>        } else if (error.error?.error?.message) {<br>          errorMessage = error.error.error.message;<br>        }<br>        <br>        this.notificationService.showError(errorMessage);<br>        return throwError(() =&gt; error);<br>      })<br>    );<br>  }<br>}</pre><h4>Why This Matters for “Professional” Design</h4><ul><li><strong>Predictability:</strong> Frontend libraries like <strong>Axios</strong> or <strong>Angular’s HttpClient</strong> are designed to automatically trigger “catch” blocks for any code in the 4xx or 5xx range. Proper codes make our frontend code much cleaner.</li><li><strong>Faster Debugging:</strong> When I see a 401 in the network tab, I immediately know it&#39;s an auth issue. I don&#39;t have to spend 10 minutes digging through JSON logs.</li><li><strong>Standardization:</strong> Mobile apps and browsers depend on these codes to decide how to handle the response (like caching or retrying a request).</li></ul><blockquote><strong><em>The Professional Rule:</em></strong><em> </em>Your HTTP Status Code should tell the story of the request. If your code is always 200 OK, you aren&#39;t using the web—you&#39;re just working around it.</blockquote><blockquote>3. The “Boring” Consistency Rule</blockquote><p>Naming conventions are often a “choose of your own adventure” experience. You might find user_id (snake_case) in the Login endpoint, but userId (camelCase) in the Profile endpoint. Or worse, one dev uses created_at while another uses date_joined.</p><p>In a <strong>Professional</strong> API, the design is intentionally “boring.” Consistency is the highest priority because it builds trust and speed for the person consuming the data.</p><h4>The Great Debate: camelCase vs snake_case</h4><p>There is no “correct” choice, only a “consistent” one. However, depending on the language your team uses, one might feel more natural:</p><ul><li><strong>camelCase</strong>: The standard for JavaScript and Frontend frameworks (e.g., isLoggedIn, userAddress).</li><li><strong>snake_case</strong>: Common in Python, Ruby, and many SQL databases (e.g., is_logged_in, user_address).</li></ul><p><strong>(Inconsistent):</strong></p><pre>// BAD: Inconsistent naming across endpoints<br>// GET /api/users/123<br>{<br>  &quot;user_id&quot;: &quot;123&quot;,           // snake_case<br>  &quot;firstName&quot;: &quot;John&quot;,        // camelCase<br>  &quot;DateJoined&quot;: &quot;2024-01-01&quot;, // PascalCase?!<br>  &quot;address&quot;: {<br>    &quot;street_name&quot;: &quot;Main St&quot;, // snake_case again<br>    &quot;city&quot;: &quot;Boston&quot;<br>  }<br>}<br><br>// POST /api/messages<br>{<br>  &quot;messageId&quot;: &quot;456&quot;,         // camelCase now?!<br>  &quot;created_at&quot;: &quot;2024-01-02&quot;  // snake_case<br>}</pre><p>This forces frontend developers to write defensive code:</p><pre>// BAD: Defensive parsing because API is unpredictable<br>getUser(id: string): Observable&lt;User&gt; {<br>  return this.http.get&lt;any&gt;(`/api/users/${id}`).pipe(<br>    map(response =&gt; ({<br>      // Manually normalize field names<br>      id: response.user_id || response.userId || response.id,<br>      firstName: response.firstName || response.first_name,<br>      joinDate: response.DateJoined || response.date_joined,<br>      address: {<br>        street: response.address?.street_name || response.address?.streetName,<br>        city: response.address?.city<br>      }<br>    }))<br>  );<br>}</pre><h4>The Solution: Pick One and Stick to It</h4><p>In the JavaScript/TypeScript ecosystem, camelCase is the natural choice:</p><pre>// GOOD: Consistent camelCase everywhere<br>// message.controller.js<br>exports.getMessage = async (req, res) =&gt; {<br>  const message = await Message.findById(req.params.id)<br>    .populate(&#39;sender&#39;, &#39;firstName lastName avatar&#39;);<br>  <br>  // Transform database fields (likely snake_case) to API camelCase<br>  const response = {<br>    messageId: message._id,<br>    content: message.content,<br>    createdAt: message.created_at,<br>    isRead: message.is_read,<br>    sender: {<br>      userId: message.sender._id,<br>      fullName: `${message.sender.first_name} ${message.sender.last_name}`,<br>      avatarUrl: message.sender.avatar_url<br>    }<br>  };<br>  <br>  res.json({ data: response });<br>};</pre><ul><li><strong>Predictability:</strong> As a frontend developer, I should be able to guess the name of a field before I even see the response. If the rest of the app uses camelCase, I know exactly how to map your data to my TypeScript interfaces without double-checking.</li><li><strong>Reduced Mental Load:</strong> When the API is consistent, I don’t have to constantly switch my brain between different naming styles. I can stay in the flow of building the UI.</li><li><strong>Fewer Bugs:</strong> Inconsistent naming leads to typos (e.g., trying to access user.userId when the API sent user.user_id). These are the most annoying bugs to track down because the code &quot;looks&quot; right but the data is undefined.</li></ul><blockquote><strong><em>The Professional Rule:</em></strong><em> </em>Pick a standard and stick to it . If you choose snake_case, use it for every key, in every object, in every endpoint. A professional API should feel like it was written by a single person, even if it was built by a team of fifty.</blockquote><blockquote>4. Designing for the Client, Not the Database</blockquote><p>In API design, your <strong>MongoDB</strong> collection is the warehouse. Your <strong>API Response</strong> is the clean product page. Professional design means transforming your data so the client (the Frontend) gets exactly what it needs — no more, no less.</p><p>The “Mirror” Trap</p><p>In Node.js, it’s easy to just pass the database object directly to the response. But MongoDB often includes internal fields like __v or sensitive fields like password_hash that the frontend should never see.</p><p><strong>The “It Works” Way (Database Mirror)</strong></p><pre>// GET /users/5<br>// Direct output from MongoDB<br>{<br>  &quot;_id&quot;: &quot;65f1a2b3c4d5e6f7g8h9&quot;,<br>  &quot;first_name&quot;: &quot;Jane&quot;,<br>  &quot;last_name&quot;: &quot;Doe&quot;,<br>  &quot;password_hash&quot;: &quot;$2b$10$K9...&quot;, // SECURITY RISK!<br>  &quot;__v&quot;: 0,                        // Internal Mongo versioning<br>  &quot;internal_flags&quot;: [&quot;is_beta_user&quot;]<br>}</pre><p><strong>The Professional Way (Client-Focused):</strong></p><pre>// GET /users/5<br>// Cleaned and formatted for the Frontend<br>{<br>  &quot;id&quot;: &quot;65f1a2b3c4d5e6f7g8h9&quot;, <br>  &quot;fullName&quot;: &quot;Jane Doe&quot;,         // Merged for easier UI display<br>  &quot;isBetaParticipant&quot;: true       // Renamed for clarity<br>}</pre><h4>Why This Matters for “Professional” Design</h4><ul><li><strong>Security:</strong> In Node.js, accidentally sending a password or ssn field because you &quot;mirrored the table&quot; is a common and dangerous mistake. A professional API explicitly selects the fields to return.</li><li><strong>Decoupling:</strong> If you decide to rename a field in your MongoDB collection tomorrow, you don’t have to break the frontend. You simply update your Node.js logic to map the new database name back to the old API name. The “Contract” stays the same.</li><li><strong>Reduced Payload:</strong> Frontend performance matters. If a mobile app only needs a user’s name and photo, don’t send the entire user object with 50 fields.</li></ul><blockquote><strong><em>The Professional Rule:</em></strong><em> </em>Your database structure is an internal secret. Your API is a public promise. Never let the “shape” of your MongoDB collection dictate the “shape” of your JSON response.</blockquote><blockquote>5. Planning for the Future (Versioning &amp; Pagination)</blockquote><p>Imagine you’ve built a popular app, and thousands of people are using it. One day, you realize you need to change how user profiles are stored. You deploy the update, and suddenly, every mobile app version currently in the App Store crashes. Users are furious, and your ratings plummet.</p><p>In an <strong>“It Works”</strong> API, we build for today. We assume the data set will always stay small and that our requirements will never change.</p><p>In a <strong>Professional</strong> API, we build for <strong>tomorrow</strong>. We assume the data will grow to millions of records and that our code <em>will</em> evolve. Two tools make this possible: <strong>Versioning</strong> and <strong>Pagination</strong>.</p><h4>The “V1” Insurance Policy (Versioning)</h4><p>Versioning is like a contract with a “no-surprise” clause. It tells your users: <em>“I promise not to break your app without warning.”</em></p><p>In <strong>Node.js/Express</strong>, it’s as simple as adding a prefix to your routes.</p><ul><li><strong>The “It Works” Way:</strong> /users</li><li><strong>The Professional Way:</strong> /api/v1/users</li></ul><p><strong>Why this is professional:</strong> If you need to make a massive change (like switching from fullName to firstName and lastName), you don&#39;t have to break your existing app. You simply create /api/v2/users. The old mobile apps continue to use v1, while the new ones move to v2. No chaos, no emergency fixes.</p><pre>// routes/v1/user.routes.js - Original version<br>router.get(&#39;/&#39;, userControllerV1.getUser);<br><br>// routes/v2/user.routes.js - Improved version with new features<br>router.get(&#39;/&#39;, userController_V2.getUser); <br>router.get(&#39;/:id&#39;, userController_V2.getUserById);<br><br>// app.js - Mount different versions<br>app.use(&#39;/api/v1/user&#39;, require(&#39;./routes/v1/user.routes&#39;));<br>app.use(&#39;/api/v2/user&#39;, require(&#39;./routes/v2/user.routes&#39;));</pre><h4>Handling the “Data Tsunami” (Pagination)</h4><p>If you have a <strong>MongoDB</strong> collection with 50,000 users and your Node.js code does a simple User.find(), your server is going to struggle. It will consume massive amounts of memory, slow down the response time, and potentially crash the user&#39;s browser as it tries to render 50,000 rows of data.</p><p>Professional APIs never return “everything.” They return data in manageable chunks.</p><p>(Don’t Do this)</p><pre>// GET /users<br>const users = await User.find(); // Dangerous if the collection is large<br>res.json(users);</pre><p><strong>The Professional Way:</strong> Use query parameters like page and limit. In MongoDB, this is easily handled with .skip() and .limit().</p><pre>// GET /users?page=1&amp;limit=10<br>const page = parseInt(req.query.page) || 1;<br>const limit = parseInt(req.query.limit) || 10;<br><br>const users = await User.find()<br>  .skip((page - 1) * limit)<br>  .limit(limit);<br><br>const total = await User.countDocuments();<br><br>res.json({<br>  data: users,<br>  meta: {<br>    totalItems: total,<br>    currentPage: page,<br>    totalPages: Math.ceil(total / limit)<br>  }<br>});</pre><h4>Why This Matters for “Professional” Design</h4><ul><li><strong>Scalability:</strong> Whether you have 10 users or 10 million, your API response time stays consistent because you’re only ever processing 10–20 items at a time.</li><li><strong>Performance:</strong> Smaller JSON payloads mean faster downloads for users on slow mobile networks.</li><li><strong>Better UX:</strong> By providing meta data (like totalPages), you give frontend developers exactly what they need to build a &quot;Next/Previous&quot; button or a numbered pagination bar.</li></ul><blockquote><strong><em>The Professional Rule:</em></strong> If you aren’t versioning, you’re building a house of cards. If you aren’t paginating, you’re building a ticking time bomb. Professional APIs are designed to handle growth gracefully.</blockquote><blockquote>6. Structured Error Handling</blockquote><p>Imagine you’re trying to log into an app, but it keeps failing. The app simply says: <em>“Error occurred.”</em> Was your password wrong? Is the server down? Did you forget to verify your email? You have no idea, and you’re likely to give up and delete the app.</p><p>If error handling is an afterthought. We often return a simple string or, even worse, a giant HTML stack trace from Node.js that exposes our internal file paths and logic.</p><p>In a <strong>Professional</strong> API, errors are treated as first-class citizens. They are part of the API contract, designed to tell the client (and the developer) exactly what went wrong and how to fix it.</p><h4>The Problem with “Vague” Errors</h4><p>When a Node.js server crashes or a MongoDB validation fails, the default behavior isn’t always helpful. Returning a 1:1 error from a library can be dangerous and confusing.</p><p><strong>The “It Works” Way:</strong></p><pre>// res.status(500).send(err.message);<br>&quot;User validation failed: email: Error, expected `email` to be unique. Value: &#39;test@me.com&#39;&quot;</pre><p><em>Why this is bad:</em> It’s unstructured text. A frontend developer can’t easily write code to “read” this string and show a specific red box under the email input.</p><h4>The Professional Way: The Standard Error Object</h4><p>A professional API returns a <strong>structured JSON object</strong>. This allows the frontend to programmatically decide what to show the user.</p><p><strong>The Professional Format:</strong></p><pre>{<br>  &quot;error&quot;: {<br>    &quot;status&quot;: 422,<br>    &quot;code&quot;: &quot;VALIDATION_ERROR&quot;,<br>    &quot;message&quot;: &quot;The provided data is invalid.&quot;,<br>    &quot;details&quot;: [<br>      {<br>        &quot;field&quot;: &quot;email&quot;,<br>        &quot;issue&quot;: &quot;ALREADY_EXISTS&quot;,<br>        &quot;message&quot;: &quot;This email is already registered.&quot;<br>      }<br>    ]<br>  }<br>}</pre><h4>Implementing This in Node.js (Express)</h4><p>The most professional way to handle this is by creating a <strong>Global Error Middleware</strong>. Instead of writing try/catch in every single route, you funnel everything into one place</p><pre>// Custom Error Class<br>class AppError extends Error {<br>  constructor(message, statusCode, code) {<br>    super(message);<br>    this.statusCode = statusCode;<br>    this.code = code;<br>  }<br>}<br><br>// Global Error Handler Middleware<br>const globalErrorHandler = (err, req, res, next) =&gt; {<br>  const statusCode = err.statusCode || 500;<br>  <br>  res.status(statusCode).json({<br>    error: {<br>      status: statusCode,<br>      code: err.code || &#39;INTERNAL_SERVER_ERROR&#39;,<br>      message: err.message || &#39;Something went wrong on our end.&#39;<br>    }<br>  });<br>};</pre><h3>Why This Matters for “Professional” Design</h3><ul><li><strong>Predictability for Frontend:</strong> As a frontend developer, I can write one single utility function to handle all API errors. Because the structure is always the same, my code becomes cleaner and more robust.</li><li><strong>Security:</strong> A professional error handler filters out technical details (like SQL/Mongo queries or stack traces) in production, while still showing them in development.</li><li><strong>Internationalization (i18n):</strong> By providing a machine-readable code (like AUTH_EXPIRED), the frontend can translate that code into any language for the user, regardless of what the server-side message says.</li></ul><blockquote><strong><em>The Professional Rule:</em></strong><em> Success responses are only half of your API. Professional design ensures that your error responses are just as helpful, structured, and predictable as your data.</em></blockquote><h3>Conclusion: Building Trust Through Professional Design</h3><p>After four years of full-stack development, I’ve learned that professional API design is about empathy. It’s about understanding the person on the other side of the wire — the frontend developer who will consume your API.</p><p>A professional API:</p><ul><li>Speaks HTTP fluently (proper methods, status codes)</li><li>Is ruthlessly consistent (naming, structure, errors)</li><li>Hides implementation details (database structure, internal fields)</li><li>Plans for the future (versioning, pagination)</li><li>Makes errors helpful (structured, actionable)</li></ul><p>When you build APIs this way, you’re not just returning JSON — you’re building trust. Your frontend team can stop guessing and start building. They can write cleaner code, catch bugs earlier, and ship features faster.</p><p>And honestly? That’s the best part of this job: building systems that make other developers’ lives easier.</p><p><em>Have you built Node.js APIs that frustrated your frontend team? What principles have you learned? Share your experiences in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0dd4306300c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/designing-rest-apis-that-your-frontend-can-actually-trust-b0dd4306300c">Designing REST APIs That Your Frontend Can Actually Trust</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Integrated a JavaScript Library into My Angular App (and Handled JS Callbacks)]]></title>
            <link>https://medium.com/@bhaskarpaleti70366/how-i-integrated-a-javascript-library-into-my-angular-app-and-handled-js-callbacks-35a9f2dd32b9?source=rss-ef8d79a19685------2</link>
            <guid isPermaLink="false">https://medium.com/p/35a9f2dd32b9</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Bhaskar]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 05:08:20 GMT</pubDate>
            <atom:updated>2025-06-30T05:13:30.649Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>⚠️ <strong>Note:</strong> Read till the end — because I made a small mistake that cost me hours in dev! Don’t get stuck on the same thing.</blockquote><p>Recently, while working on an Angular project, I came across a situation where I had to integrate a plain JavaScript library. Everything was going great — until I had to trigger a JS function from Angular <strong>and</strong> handle callbacks from JS back into Angular.</p><p>If you’ve ever dealt with third-party SDKs, widgets, or legacy JS scripts in Angular, you’ll probably relate.</p><p>Let me walk you through how I handled both cases with some clean and simple code.</p><h4>1. Integrating a Custom JavaScript File into Angular :</h4><p>To start with, I created a separate JavaScript file inside the assets folder of my Angular application. This is the recommended place for custom JS files since anything placed here can be easily accessed by the Angular app.</p><p>In this file, I declared a function called redirectToLibrary, which accepts a token from the Angular component. Along with the token, I passed a config object containing three callback methods: onSuccess, onProgress, and onError. These callbacks get triggered based on the asynchronous response from the third-party library method.</p><p>Here’s what the JS file looks like:</p><pre>function onSuccess(event) {};<br>function onProgress(event) {};<br>function onError(event) {};<br><br>function redirectToLibrary(token) {<br>    let config = {<br>        onSuccess,<br>        onProgress,<br>        onError<br>    };<br>    return  Library.someMethod(token,config).then((res)=&gt;{<br>        return res;<br>    });<br>}</pre><pre>&quot;build&quot;: {<br>     &quot;options&quot;: { <br>          &quot;scripts&quot;: [&quot;src/assets/js/mylibrary.js&quot;],<br>          &quot;styles&quot; : []<br>      },<br>  }</pre><p>After writing this file, I updated the angular.json file to include the JS file path under the scripts array. This ensures that the methods inside the JS file are globally available in the Angular project once it loads.</p><h4>2. Handling JavaScript Callbacks in Angular :</h4><p>Since we already included the JavaScript file in the angular.json file, we can now access the JS methods in our Angular component using the window object.</p><p>Before doing that, it’s a good idea to update the global Window interface in TypeScript to include the custom JS methods we plan to use. This prevents TypeScript errors and gives us proper type checking.</p><pre>declare global {<br>  interface Window {<br>    redirectToLibrary: (token: string) =&gt; Promise&lt;any&gt;;<br>    onSuccess: (event: any) =&gt; void;<br>    onProgress: (event: any) =&gt; void;<br>    onError: (event: any) =&gt; void;<br>  }<br>}</pre><p>Next, we assign these global window methods to local component methods using .bind(this). This ensures that when the JavaScript library triggers a callback, the corresponding Angular method is called with the correct context.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.scss&#39;]<br>})<br>export class AppComponent implements OnInit {<br>  title = &#39;angular&#39;;<br><br>  ngOnInit() {<br>    window.onSuccess = this.onSuccess.bind(this);<br>    window.onProgress = this.onProgress.bind(this);<br>    window.onError = this.onError.bind(this);<br>  }<br><br>  onRedirectToLibrary(token:string){<br>     window.redirectToLibrary(token).then((res:any)=&gt;{<br>         console.log(&#39;Response:&#39;, res)<br>     })<br>  }<br><br>  onSuccess(data: any) {<br>    console.log(&#39;Success:&#39;, data);<br>    // Add any success logic here, like updating UI or routing<br>  }<br><br>  onProgress(data: any) {<br>    console.log(&#39;Progress:&#39;, data);<br>    // Show loading indicator or progress bar update<br>  }<br><br>  onError(data: any) {<br>    console.error(&#39;Error:&#39;, data);<br>    // Display error message or retry option<br>  }<br>}</pre><pre>&lt;button (click)= &quot;onRedirectToLibrary(&#39;myToken&#39;)&quot;&gt;Redirect&lt;/button&gt;</pre><p>When the <strong>“Redirect”</strong> button is clicked, it triggers the onRedirectToLibrary() method in the Angular component, passing a token (in this case, &#39;myToken&#39;) as a parameter. Inside this method, we call the globally available redirectToLibrary() function from the JavaScript file using the window object. Once the promise is resolved, we log the response to the console. This sets up a seamless flow between Angular and the external JavaScript library.</p><h4>3. The Bugs That Wasted My Time in Dev :</h4><blockquote>Bug 1: I Missed a Semicolon After an Object Declaration :</blockquote><p>Another tricky bug came from a <strong>missing semicolon</strong> in the JS file. Here’s what I had originally:</p><pre>function redirectToLibrary(token) {<br>    let config = {<br>        onSuccess,<br>        onProgress,<br>        onError<br>    } // ← missing semicolon<br><br>    return  Library.someMethod(token,config).then((res)=&gt;{<br>        return res;<br>    });<br>}</pre><p>Locally, this ran fine. But in the <strong>dev environment</strong>, it failed silently.</p><p>JavaScript’s automatic semicolon insertion (ASI) treated the code like this:</p><pre>const config = {<br>  onSuccess,<br>  onProgress,<br>  onError<br>}(function() { ... })();</pre><p>So it tried to execute the object as a function — which obviously doesn’t work.</p><h4>Pro Tip<strong>:</strong></h4><p>As frontend developers, we often overlook the importance of JavaScript rules — especially when code works locally. But I learned the hard way that even a tiny syntax issue, like a missing semicolon or using any, can break your app in production.<br> <strong>Always double-check your JavaScript basics if you get stuck like I did. It might save you hours!</strong></p><blockquote>Bug 2: I Used window as any Instead of Extending the Window Interface:</blockquote><p>To quickly get around TypeScript errors, I initially used:</p><pre>(window as any).redirectToLibrary(token);</pre><p>It worked fine in my <strong>local environment</strong>, so I didn’t think much of it. But in the <strong>dev environment</strong>, the behavior became inconsistent. Sometimes the callbacks didn’t fire, or the method wasn’t even recognized on the window object.</p><p>That’s when I realized the right way to do this is to <strong>extend the global </strong><strong>Window interface</strong>, which avoids casting to any and gives you proper type safety.</p><p>The correct approach:</p><pre>declare global {<br>  interface Window {<br>    redirectToLibrary: (token: string) =&gt; Promise&lt;any&gt;;<br>    onSuccess: (event: any) =&gt; void;<br>    onProgress: (event: any) =&gt; void;<br>    onError: (event: any) =&gt; void;<br>  }<br>}</pre><p>This ensures your TypeScript environment understands those global methods and protects you from misspellings or invalid usage.</p><h3>🙌 Stay Connected</h3><p>If you found this helpful, feel free to <strong>follow me</strong> here on Medium for more real-world tips, bug fixes, and insights from my journey as a frontend developer. I regularly share practical solutions around <strong>Angular, React</strong>, <strong>JavaScript</strong>, <strong>TypeScript</strong>, and other frontend challenges.</p><p>Thanks for reading — and happy coding! 💻✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a9f2dd32b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>