<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Angular &#8211; Chris Philbin&#039;s Blog</title>
	<atom:link href="https://www.chrisphilbin.net/category/angular/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.chrisphilbin.net</link>
	<description>Perfection Through Persistence.</description>
	<lastBuildDate>Tue, 11 Jun 2024 03:01:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.2</generator>
	<item>
		<title>Using the async pipe within Angular templates to perform control flow</title>
		<link>https://www.chrisphilbin.net/using-the-async-pipe-within-angular-templates-to-perform-control-flow/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 18 Oct 2023 23:47:44 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=438</guid>

					<description><![CDATA[If you&#8217;re working on a small to mid-sized Angular app, chances are you&#8217;re probably not using a state management library like NgRx to handle your app&#8217;s state. And that&#8217;s probably&#8230;]]></description>
										<content:encoded><![CDATA[
<p>If you&#8217;re working on a small to mid-sized Angular app, chances are you&#8217;re probably not using a state management library like <a rel="noreferrer noopener" href="https://ngrx.io/" target="_blank">NgRx</a> to handle your app&#8217;s state. And that&#8217;s probably alright if you&#8217;re only working with maybe a dozen or so components.</p>



<p>If that&#8217;s the case, then you&#8217;re probably relying on services to manage state as it&#8217;s the out-of-the-box method presented to us by the Angular team. </p>



<p>The gist of services is to abstract away any business logic from our components, and subscribing to any state that we need to use within the component.</p>



<p>One common task that we routinely find ourselves doing when relying solely on services for state management is creating semaphore variables to determine whether or not a certain piece of state is loading and as a result displaying some kind of message or icon to the user letting them know that it may be a moment before the data is ready. Error handling also mimics this same pattern where we&#8217;re using Subjects or BehaviorSubjects and subscribing to them over and over again. Based on the truthiness of a variable like &#8220;hasErrors&#8221;, we can display a message letting the user know something unexpected happened and it requires their attention.</p>



<p>The async pipe provided to us by Angular out of the box is a great way to get around having to set up numerous subscriptions within our component TS files, and comes in especially handy when you&#8217;re working on a small to mid-sized application that doesn&#8217;t have extremely complex state and control flow. </p>



<p>Let&#8217;s take a look at the traditional way of setting up a simple service and a method to fetch some data from an external API, and then subscribe to that data from within a component:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { Injectable } from &#039;@angular/core&#039;;
import { BehaviorSubject, of } from &#039;rxjs&#039;;
@Injectable({
  providedIn: &#039;root&#039;,
})
export class CounterService {
  count$: BehaviorSubject&lt;number&gt; = new BehaviorSubject&lt;number&gt;(0);
  isLoading$: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject&lt;boolean&gt;(false);
  constructor() {}
  increase() {
    this.isLoading$.next(true);
    setTimeout(() =&gt; {
      this.count$.next(this.count.value + 1);
      this.isLoading$.next(false);
    }, 3500);
  }
}
</pre></div>


<p>The above service is somewhat contrived, but it&#8217;s a good example to show us how subscribing to the isLoading variable can be abstracted away using the async pipe within our component template files. Let&#8217;s take a look at how how we&#8217;d implement showing the user some kind of loading prompt within the use of the async pipe:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { CounterService } from &#039;../services/counter.service&#039;;
import { Component, OnInit } from &#039;@angular/core&#039;;
@Component({
  selector: &#039;app-my-counter&#039;,
  templateUrl: &#039;./my-counter.component.html&#039;,
  styleUrls: &#x5B;&#039;./my-counter.component.scss&#039;],
})
export class MyCounterComponent implements OnInit {
  count: number;
  isLoading: boolean;
  constructor(public countService: CountService) {}
  ngOnInit(): void {
      this.countService.count$.subscribe((count) =&gt; {
        this.count = count;
      })
      this.countService.isLoading$.subscribe((isLoading) =&gt; {
        this.isLoading = isLoading;
      })
    this.countService.increase();
  }
}
</pre></div>


<p>Lines 21 &#8211; 23 are where things start to get really repetitive and you&#8217;ll find yourself setting up at least 3 subscriptions per component, assuming that each component always has some kind of meaningful external state (In our example the count variable), and semaphore variables for both loading and errors.</p>



<p>Also note: Line 14 we&#8217;re also marking the counterService <strong>public</strong> instead of <strong>private</strong> like we typically do when we handle dependency injection via the constructor&#8217;s parameters. If we did not do this, the counterService would not be available within the associated template file that we&#8217;re going to work with next.</p>



<p>Let&#8217;s abstract that away from our component TS files and implement it within our template files instead using the async pipe:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;div *ngIf=&quot;counterService.isLoading$ | async; else showCount&quot;&gt;
    Loading... Please wait!
&lt;/div&gt;
&lt;ng-template #showCount&gt;
    {{ counterService.count$ | async }}
&lt;/ng-template&gt;
</pre></div>


<p>What a difference! We no longer have to set up subscriptions within our component TS files but can instead lean on the async pipe to manage the subscriptions and assignments for us!</p>



<p>The async pipe is great because it subscribes to the observable stream and takes whatever values comes across the stream and interpolates it within the template without us having to specifically initialize a local template variable and handle the assignment based on the subscription.</p>



<p>Just to be clear, this will work when working with not-so-complex states generally found in smaller to mid-sized apps. This pattern starts to break down once you start introducing things like role based authentication, really in depth control flow, or a more complex object with nested objects and other data structures and collections.</p>



<p></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>The Differences Between Subjects and BehaviorSubjects in RxJS</title>
		<link>https://www.chrisphilbin.net/the-differences-between-subjects-and-behaviorsubjects-in-rxjs/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Wed, 16 Aug 2023 23:59:00 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[RxJS]]></category>
		<category><![CDATA[Typescript]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=315</guid>

					<description><![CDATA[If you&#8217;re just starting to dive into Angular you&#8217;ve probably quickly realized that it&#8217;s a lot different from the other major front end frameworks such as React and Vue. Angular&#8230;]]></description>
										<content:encoded><![CDATA[
<p>If you&#8217;re just starting to dive into Angular you&#8217;ve probably quickly realized that it&#8217;s a lot different from the other major front end frameworks such as React and Vue. Angular is a &#8220;convention over configuration&#8221; framework in the sense that the Angular development team has designed the framework in such a way to more or less <em>force</em> you into following a certain set of rules in order for it to work properly. (I&#8217;ve personally found Vue to be a happy medium in between Angular and React in this sense)</p>



<p>If you&#8217;re a less experienced front end developer and are looking to up your JavaScript game, forcing yourself to create a few Angular apps is a great way to really level up your JS skill set. React and Vue do a great job at abstracting things away so some things that happen just seem like magic. Angular still has abstractions however not to the extent of the other two so you&#8217;re forced to roll up your sleeves and up your JS game. (This is really just me saying the learning curve for Angular is more demanding that any other front end framework.)</p>



<p>Angular ships with RxJS and it&#8217;s a complete paradigm shift in that you no longer simply rely on fetch() or axios.get() to handle your HTTP requests in your app. RxJS instead allows us as developers to <em>subscribe</em> to a data stream and listen to it for any changes while the subscription is active. To be fair, you can implement RxJS in either a React or Vue app, but neither ships with it out of the box so it&#8217;s up to you the install it as a dependency and use it (Convention over configuration&#8230; Remember?)</p>



<p>Subjects and BehaviorSubjects are observables that can emit their values to multiple observers via subscriptions. On the surface we&#8217;re almost inclined to think that both a Subject and a BehaviorSubject do the same thing, but the differences are subtle and can make a pretty big impact on your application.</p>



<p>In simple terms: <strong>A Subject does not need to have an initial value when being created but a BehaviorSubject requires an initial value when being created.</strong> Therefore, a Subject will only emit upcoming values, whereas a BehaviorSubject will emit <em>one previous value and all upcoming values</em>.</p>



<p>Let&#8217;s set the stage for a pretty common example front end developers handle on a routine basis: showing or hiding a modal to let the user edit settings. As you can imagine, this is a good use case for a BehaviorSubject because we&#8217;ll want to set the initial value of &#8220;showModal&#8221; to &#8220;false&#8221;.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
// src/app/services/modal.service.ts

import { BehaviorSubject } from &#039;rxjs&#039;;

export class ModalService {
  showModal = new BehaviorSubject&lt;boolean&gt;(false);

  toggleModal() {
    this.showModal.next(!this.showModal.value);
  }
}
</pre></div>


<p>Had we not passed in a boolean value to the BehaviorSubject&#8217;s constructor, TypeScript would have immediately given us an error indicating that one argument was expected, but we&#8217;ve given it 0.</p>



<p>The above example sets up an Angular service that we can then import into any other component and utilize the toggleModal() method. Any subscriptions to this observable therefore will receive an initial value of &#8220;false&#8221; since BehaviorSubjects allow us to track and initial value and any subsequent changes in the future.</p>



<p>On the other hand, a Subject does not require an initial value. In sticking with the modal example from above, a good parallel use case for a Subject would be if upon the user opening a modal in the app we want to display a form containing the app&#8217;s settings that they can modify and then save. Let&#8217;s take a look:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
// src/app/services/settings.service.ts

import { Subject } from &#039;rxjs&#039;;
import { HttpClient } from &#039;@angular/common/http&#039;;

export class SettingsService {

  appSettings = new Subject&lt;Settings&gt;();

  constructor(private http: HttpClient) {}

  getAppSettings() {
  this.http.get&lt;Settings&gt;(&#039;https://www.myapp_api.com/settings&#039;)
    .subscribe((settings: Settings) =&gt; {
      console.log(settings, &#039;Settings received from API call.&#039;);
      this.settings.next(settings);
    )};
  }

}
</pre></div>


<p>Sure, there&#8217;s a little more code than the previous BehaviorSubject example but most of it is simply boiler plate code in order to set things up. The key takeaway here should be that when we create a new Subject, we do not have to supply its constructor method with an argument to set the initial value upon creation. We only have to indicate what kind of value will be occupying it in the future, which in this case is an object of type &#8220;Settings&#8221;.</p>



<p>We&#8217;ve defined a getAppSettings() method that we can again import into any other component and fetch our user&#8217;s app settings from the back end and then once the request comes back we will push the new value via the next() method and any subscriptions made will finally receive their first value. We will then have access to the app settings, now stored with the label <strong>appSettings</strong>, be it an object of settings or an array.</p>



<p>So what&#8217;s the tl;dr version of all of this? Pretty simple, actually:</p>



<p><strong>Use a BehaviorSubject if you need an initial value (The modal example above is a really good example) and use a Subject if you do not need an initial value.</strong></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Unit Testing Components in Angular</title>
		<link>https://www.chrisphilbin.net/unit-testing-components-in-angular/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Thu, 27 Jul 2023 00:58:43 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://chrisphilbin.net/?p=365</guid>

					<description><![CDATA[Test-Driven development, or TDD, is a paradigm in which before any code is written, tests are first created based off of requirements/user stories. We can think of it similar to&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Test-Driven development, or TDD, is a paradigm in which before any code is written, tests are first created based off of requirements/user stories. We can think of it similar to a &#8220;to do&#8221; list of things that a piece of software must do in order to satisfy the requirements. Throughout the development process, these tests are run in order to ensure that no breaking changes or bugs have been introduced. </p>



<p>A <em><strong>unit test</strong></em> is a smaller piece of the TDD paradigm in which it sets out to test a single unit of code &#8211; in most cases a function or method &#8211; to ensure that when it runs in a controlled environment the code behaves as we intended it to do so.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img fetchpriority="high" decoding="async" src="https://chrisphilbin.net/wp-content/uploads/2023/07/pencil-test.jpeg" alt="" class="wp-image-426" width="507" height="341"/></figure></div>


<p>When we say <strong><em>unit testing</em></strong> as it relates to Angular, in most cases we&#8217;re talking about testing a single component to ensure that its functionality works as intended and no breaking changes have been introduced. (We can also unit test services, directives, and pipes) By default, Angular comes out of the box with Jasmine and Karma to assist with unit testing. <a href="https://jasmine.github.io/index.html">Jasmine</a> is a testing framework that gives us things such as spies and pattern matching, whereas <a href="https://karma-runner.github.io/6.4/index.html">Karma</a> is a task runner that helps us with the execution of the tests.</p>



<p>When we generate a new component using the Angular CLI (<em>ng generate component users</em>) in addition to it generating our usual CSS, HTML template, and TS Class file, it also generates a .spec.ts file for us that scaffolds a basic test for us that ensures the component is at least successfully created. Certainly a great starting point!</p>



<p>Let&#8217;s take a look at what the CLI gives us after running the above <em>ng generate</em> command:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
import { ComponentFixture, TestBed } from &#039;@angular/core/testing&#039;;

import { UsersComponent } from &#039;./users.component&#039;;

describe(&#039;UsersComponent&#039;, () =&gt; {
  let component: UsersComponent;
  let fixture: ComponentFixture&lt;UsersComponent&gt;;

  //SECTION 1
  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: &#x5B; UsersComponent ]
    })
    .compileComponents();
  });

  //SECTION 2
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UsersComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  //SECTION 3
  it(&#039;should create&#039;, () =&gt; {
    expect(component).toBeTruthy();
  });
});
</pre></div>


<p>I&#8217;ve added several comments to act as section headers to better assist in explaining what&#8217;s going on.</p>



<p><strong>Section 1</strong><br>This beforeEach block runs before each test we define later on in the spec file. We&#8217;re setting up a Test Bed, which is a controlled Angular environment for our tests to run in. Notice how the configureTestingModule method takes in an object as its argument and within that object we have a declarations property that is an array. Where else have we seen this? When ever we declare a module using the @NgModule decorator, of course! We&#8217;re essentially setting up a mini-module to test our component in!</p>



<p><strong>Section 2</strong><br>This second beforeEach block is where we&#8217;ll actually be setting up an instance of the component we want to test.<br><br>TestBed.createComponent(UsersComponent) returns to us a TestBed with an instance of the UsersComponent, and on the very next line we&#8217;re setting our component variable to fixture.componentInstance property which is an instance of our component that we can now run tests on!<br><br>fixture.detectChanges() gives us access to any changes to the component &#8211; it&#8217;s essentially refreshing the component after we&#8217;ve run a method or made some changes to some of the component&#8217;s properites.<br><br><strong>Section 3</strong><br>Finally! What we&#8217;ve been waiting for! Section 3 is where we&#8217;re actually writing our tests &#8211; Remember before each of these tests run, sections 1 and 2 will run each time &#8211; hence the beforeEach blocks. This boiler plate test lets us know that the component is created successfully without any bugs that are preventing it from compiling/loading.</p>



<h2 class="wp-block-heading">Putting it all together</h2>



<p>Let&#8217;s take things a step further. Let&#8217;s create a test for a login form that should only attempt to authenticate a user if the username and password fields are filled out. This is a great example because not only is it a real world use case, but it&#8217;ll also show us how to incorporate spies into our unit tests. Our login form also relies on a service, in this case the authService, so it&#8217;ll also give us a chance to look at how we incorporate services into our tests as well.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
import { ComponentFixture, TestBed } from &#039;@angular/core/testing&#039;;
import { FormsModule, NgForm } from &#039;@angular/forms&#039;;
import { AppRoutingModule } from &#039;src/app/app-routing.module&#039;;
import { AuthService } from &#039;src/app/services/auth.service&#039;;

import { LoginComponent } from &#039;./login.component&#039;;

const authServiceStub = {
  login: () =&gt; {},
  signup: () =&gt; {},
  user: {
    subscribe: () =&gt; {},
  },
};

describe(&#039;LoginComponent&#039;, () =&gt; {
  let component: LoginComponent;
  let authService: AuthService;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: &#x5B;LoginComponent],
      imports: &#x5B;AppRoutingModule, FormsModule],
      providers: &#x5B;{ provide: AuthService, useValue: authServiceStub }],
    }).compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    authService = TestBed.inject(AuthService);
  });

  it(&#039;Should not attempt to authenticate user if the form is invalid&#039;, () =&gt; {
    const authSpy = spyOn(authService, &#039;login&#039;);
    const testFormData = &lt;NgForm&gt;{
      valid: false,
      value: {
        email: &#039;&#039;,
        password: &#039;&#039;,
      },
    };
    component.onSubmit(testFormData);
    fixture.detectChanges();
    expect(authSpy).toHaveBeenCalledTimes(0);
  });
});
</pre></div>


<p>A few important things to take note of that differ from the boiler plate code the Angular CLI gives us:<br></p>



<ul class="wp-block-list">
<li>We create an object called authServiceStub that stubs out all of the methods/properties that our login component will interact with. In the majority of cases it&#8217;s alright to just create no-op functions. We can run them, but we don&#8217;t expect anything to happen. We can spy on them to see if they do or do not run, and how many times if they do run.</li>



<li>The login component relies on the AppRoutingModule as well as the FormsModule. These must be imported into our test module via the imports array.</li>



<li>We need to provide the AuthService to this module, but we don&#8217;t want to test the logic within the service itself when unit testing this component. At this point we don&#8217;t really care <em>how</em> the service&#8217;s login and signup methods work. We just want to ensure that our login component actually runs them when expected. We&#8217;ll more or less overwrite most of its functionality via the <em>useValue</em> property.</li>



<li>We inject the new mock AuthService into the TestBed so we can later interact with it and spy on its methods.</li>
</ul>



<p>Lastly, let&#8217;s take a look at the single <strong><em>it</em></strong> spec from above:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
  it(&#039;Should not attempt to authenticate user if the form is invalid&#039;, () =&gt; {
    const authSpy = spyOn(authService, &#039;login&#039;);
    const testFormData = &lt;NgForm&gt;{
      valid: false,
      value: {
        email: &#039;&#039;,
        password: &#039;&#039;,
      },
    };
    component.onSubmit(testFormData);
    fixture.detectChanges();
    expect(authSpy).toHaveBeenCalledTimes(0);
  });
</pre></div>


<p>We&#8217;re doing a few important things here:</p>



<ul class="wp-block-list">
<li>We&#8217;re creating a spy. We&#8217;re going to spy on the login method from our newly created authService that we injected into this test bed.</li>



<li>We&#8217;re setting up basic form data that we know should result in the login function not running.</li>



<li>We attempt to run the component&#8217;s onSubmit function with the testFormData as an argument and we&#8217;re refreshing to get any changes.</li>



<li>Finally, we&#8217;re checking to see how many times the login function was run thanks to the authSpy. We&#8217;re expecting this value to be 0. If it&#8217;s been run 1 or more times the test will fail and we know that we introduced breaking changes into our code. (Did we remove a conditional, perhaps?)</li>
</ul>



<h2 class="wp-block-heading">What about DOM elements?</h2>



<p>The above example didn&#8217;t verify that an error message was being presented to the user, which would be somewhat of an awkward user experience if we just left them guessing as to why nothing is happening while using the application. How would we go about creating a unit test that also ensures that some kind of error message is being shown to the user? Let&#8217;s take a look at another <strong><em>it</em></strong> block:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
  it(&#039;Should display a div that contains an error message in the event of a user error during login&#039;, () =&gt; {
    const testFormData = &lt;NgForm&gt;{
      valid: false,
      value: {
        email: &#039;&#039;,
        password: &#039;&#039;,
      },
      reset: () =&gt; {},
    };
    component.onSubmit(testFormData);
    fixture.detectChanges();
    const loginElement: HTMLElement = fixture.nativeElement;
    expect(loginElement.querySelector(&#039;#error-container&#039;)?.innerHTML).toContain(
      &#039;Must provide valid credentials&#039;
    );
  });
</pre></div>


<p>A lot of this is pretty similar to the previous example. The main difference is that after we attempt to submit the form with data that we know will cause it to fail, we run fixture.detectChanges() to &#8220;refresh&#8221; the component, and then we access the underlying HTML element via fixture.nativeElement. We then create an expect/toContain check that accesses the HTML element that has <strong>error-container</strong> as its ID and ensures that its innerHTML contains the string &#8220;Must provide valid credentials&#8221;.</p>



<h2 class="wp-block-heading">Wrapping things up</h2>



<p>Overall, unit testing can be challenging, but as an application grows and development teams have to move faster, it speeds up the overall development process and decreases errors going into production because you can immediately check to see if the changes you are making have unintended consequences elsewhere in the application. It&#8217;s also important to note that as a best practice, it&#8217;s best to write the majority of tests <em>before</em> writing any code in order to ensure you&#8217;re not introducing biases &#8211; It is <strong><em>test driven</em></strong> development, afterall!</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
