<?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[BrieBug Blog - Medium]]></title>
        <description><![CDATA[Expert Angular Consulting and Training - Medium]]></description>
        <link>https://medium.com/briebug-blog?source=rss----a8a798084f9e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>BrieBug Blog - Medium</title>
            <link>https://medium.com/briebug-blog?source=rss----a8a798084f9e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:47:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/briebug-blog" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Internationalizing your Angular app]]></title>
            <link>https://medium.com/briebug-blog/internationalizing-your-angular-app-aeebb4e50bfe?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/aeebb4e50bfe</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[i18n]]></category>
            <dc:creator><![CDATA[Jamie Perkins]]></dc:creator>
            <pubDate>Thu, 05 Sep 2019 19:52:06 GMT</pubDate>
            <atom:updated>2021-02-03T17:52:23.319Z</atom:updated>
            <content:encoded><![CDATA[<p>A guided tour of your options and how to implement them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OssHQA580t6HNzHMdmZ-WQ.jpeg" /><figcaption>“We are the world, we are the children… 🎶”</figcaption></figure><p>Supporting a user’s locale and language is an often overlooked but important way to make your app user-friendly. When you internationalize your app, you’ve taken an important step in making your app accessible and usable for more users around the world.</p><p><strong>This article has moved</strong>: <a href="https://blog.briebug.com/blog/internationalizing-your-angular-app">https://blog.briebug.com/blog/internationalizing-your-angular-app</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeebb4e50bfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/internationalizing-your-angular-app-aeebb4e50bfe">Internationalizing your Angular app</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 ways to use Angular HTTP Interceptors]]></title>
            <link>https://medium.com/briebug-blog/3-ways-to-use-angular-http-interceptors-337e1a26fd97?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/337e1a26fd97</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kevin Schuchard]]></dc:creator>
            <pubDate>Thu, 27 Jun 2019 19:47:12 GMT</pubDate>
            <atom:updated>2019-06-27T19:47:12.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3MHwF17jn0cuREoG" /><figcaption>Photo by <a href="https://unsplash.com/@bantersnaps?utm_source=medium&amp;utm_medium=referral">Banter Snaps</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>HTTP Interceptors provide a flexible mechanism to control your application when dealing with network-related resources. They’re similar to middle-ware in other frameworks and allow network logic to be abstracted and reused.</p><h4>Resources</h4><p>🚀 <a href="https://ng-interceptors.netlify.com/">Demo app</a> / 🛠 <a href="https://github.com/schuchard/ng-interceptors">Github</a></p><h3>Why use HTTP Interceptors</h3><p>Interceptors provide a convenient location to apply functionality across all or some network requests and responses. As an application grows, re-implementing the same logic can become tedious, error-prone, and potentially leads to inconsistent functionality.</p><p>For example, setting up an Authorization Header across multiple network requests can quickly lead to duplicate code at the service or component level. By utilizing an interceptor it can be configured once and applied on all existing and future HTTP requests. By abstracting global network logic to a single responsibility class, we make it easier to test and build reliable applications quickly.</p><h3>Intercepting Requests</h3><p>Requests can be controlled with the HttpHandler that is passed to interceptor methods. In its simplest usage, if you don’t want to modify the request, you return the handle method. Typically used like this:</p><pre>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler) {<br> return next.handle(req)<br>}</pre><p>This is where you can modify <a href="https://angular.io/guide/http#set-default-headers">Auth headers</a> or anything else related to the request.</p><pre>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler) {<br>  // Get the auth token from the service.<br>  const authToken = this.auth.getAuthorizationToken();</pre><pre>  // Clone the request and replace the original headers with<br>  // cloned headers, updated with the authorization.<br>  const authReq = req.clone({<br>    headers: req.headers.set(&#39;Authorization&#39;, authToken)<br>  });</pre><pre>  // send cloned request with header to the next handler.<br>  return next.handle(authReq);<br>}</pre><h3>Intercepting Responses</h3><p>To interact with the response, you’ll pipe off the handle method. From there you can interact with other services such as adding to a cache like you’ll see below or modifying the response in the XML to JSON example.</p><p>Be aware that there may be other events besides the response so it’s a good idea to check for an HttpResponse before acting on the response event.</p><pre>return next.handle(req).pipe(<br>  // There may be other events besides the response.<br>  filter(event =&gt; event instanceof HttpResponse),<br>  tap((event: HttpResponse&lt;any&gt;) =&gt; {<br>    cache.set(req.urlWithParams, {<br>      key: req.urlWithParams,<br>      body: event.body,<br>      dateAdded: Date.now(),<br>    });<br>  })<br>);</pre><h3>Examples</h3><h4>Caching</h4><p>Caching, specifically <a href="https://martinfowler.com/bliki/TwoHardThings.html">cache invalidation</a>, can be quite difficult so this article will skip the specifics on that. Instead, we’ll look at a simple example that returns something from the cache or allows the request to go through. For a given endpoint you can cache the results in a number of ways and return the cache based on time, existence, or another factor.</p><p>The following example checks for the existence in the cache and returns it:</p><pre>export class CachingInterceptor implements HttpInterceptor {<br>  constructor(private cache: CacheService) {}</pre><pre>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    // continue request if not cacheable.<br>    if (!this.canCache(req)) {<br>      return next.handle(req);<br>    }</pre><pre>const cachedResponse = this.cache.get(req.urlWithParams);<br>    // return HttpResponse so that HttpClient methods return a value<br>    return cachedResponse<br>      ? of(new HttpResponse({ body: cachedResponse.body }))<br>      : sendRequest(req, next, this.cache);<br>  }</pre><pre>canCache(req: HttpRequest&lt;any&gt;): boolean {<br>    // only cache `todo` routes<br>    return req.url.includes(&#39;todos&#39;);<br>  }<br>}</pre><p>If the request is not in the cache, make the request as normal with sendRequest.</p><pre>function sendRequest(<br>  req: HttpRequest&lt;any&gt;,<br>  next: HttpHandler,<br>  cache: CacheService<br>): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>  return next.handle(req).pipe(<br>    // There may be other events besides the response.<br>    filter(event =&gt; event instanceof HttpResponse),<br>    tap((event: HttpResponse&lt;any&gt;) =&gt; {<br>      cache.set(req.urlWithParams, {<br>        key: req.urlWithParams,<br>        body: event.body,<br>        dateAdded: Date.now(),<br>      });<br>    })<br>  );<br>}</pre><p>Here we pipe off the handle method to interact with the response and set it in the cache. Now if the same request is made it will be returned immediately.</p><pre>const cachedResponse = this.cache.get(req.urlWithParams);</pre><pre>return cachedResponse<br>  ? of(new HttpResponse({ body: cachedResponse.body }))<br>  : sendRequest(req, next, this.cache);</pre><h4>XML to JSON</h4><p>Often developers don’t have complete control over how they get data. For example, if you have one API that returns XML but the rest of your app works with JSON it might make sense to convert the XML response to JSON for consistency. With an interceptor, the XML conditional logic can be abstracted from consumers and applied to all network requests.</p><pre>export class XmlInterceptor implements HttpInterceptor {<br>  constructor(<a href="http://twitter.com/Inject">@Inject</a>(XmlParser) private xml: XMLParser) {}</pre><pre>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler) {<br>    // extend server response observable with logging<br>    return next.handle(req).pipe(<br>      // proceed when there is a response; ignore other events<br>      filter(event =&gt; event instanceof HttpResponse),<br>      map(<br>        (event: HttpResponse&lt;any&gt;) =&gt; {<br>          if (this.xml.validate(event.body) !== true) {<br>            // only parse xml response, pass all other responses to other interceptors<br>            return event;<br>          }</pre><pre>          // {responseType: text} expects a string response<br>          return event.clone({ body: JSON.stringify(this.xml.parse(event.body)) });<br>        },<br>        // Operation failed; error is an HttpErrorResponse<br>        error =&gt; event<br>      )<br>    );<br>  }<br>}</pre><p>In order to handle the response, this logic is pipe’ed off of the handle method. Then if the response is valid XML, we return the cloned response event and parse the XML into JSON.</p><h3>Redirect based on scopes</h3><p>When an application needs to restrict access to certain routes, an interceptor can provide that functionality in one place across many routes. Since interceptors are run for every request you can organize your route guard logic in one place. Assuming you’ve set up what routes are guarded and can access the user’s available scopes, the interceptor can determine whether to allow the request or redirect.</p><pre>export class ScopesInterceptor implements HttpInterceptor {<br>  constructor(private scopesService: ScopesService, private router: Router) {}</pre><pre>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler) {<br>    // not protected, pass request through<br>    if (!this.scopesService.protectedRoutes(req.urlWithParams)) {<br>      return next.handle(req);<br>    }</pre><pre>    // route is protected, only allow admins<br>    if (this.scopesService.isAdmin) {<br>      return next.handle(req);<br>    } else {<br>      // not admin, redirect and cancel request<br>      this.router.navigate([&#39;404&#39;]);<br>      return of(undefined);<br>    }<br>  }<br>}</pre><p>In this example, if the route isn’t protected we don’t take any action. If it is the request is allowed if the user is an admin otherwise we redirect and cancel the request.</p><h4>Immutability</h4><p>It may not be obvious but the HttpRequest and HttpResponse instances are immutable. From the <a href="https://angular.io/guide/http#immutability">Angular docs</a></p><blockquote>interceptors are capable of mutating requests and responses, the HttpRequest and HttpResponse instance properties are read-only, rendering them largely immutable.</blockquote><p>This is done because the app may retry a request several times and if the interceptor could modify the original request then each subsequent request could be different.</p><p>What this means for developers is that you must clone the request and modify that instance:</p><pre>// clone request and replace &#39;<a href="http://&/#39;">http://&#39;</a> with &#39;<a href="https://&/#39;">https://&#39;</a> at the same time<br>const secureReq = req.clone({<br>  url: req.url.replace(&#39;<a href="http://&/#39;">http://&#39;</a>, &#39;<a href="https://&/#39;">https://&#39;</a>)<br>});</pre><pre>// send the cloned, &quot;secure&quot; request to the next handler.<br>return next.handle(secureReq);</pre><h4>Interceptor order</h4><p>Interceptors pass requests through in the order that they’re <a href="https://angular.io/guide/http#provide-the-interceptor,">provided</a> [A,B,C]. The following “barrel” example gathers interceptors to later be provided in their declared order.</p><blockquote>requests will flow in A-&gt;B-&gt;C and responses will flow out C-&gt;B-&gt;A.</blockquote><pre>export const httpInterceptorProviders = [<br>  { provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true },<br>];</pre><p>then in app.module.ts:</p><pre>providers: [<br>  httpInterceptorProviders<br>],</pre><h3>Summary</h3><p>As we’ve seen in these examples, interceptors provide a straightforward mechanism to interact with HTTP requests and responses. This makes it easy to add layers of control and provide more functionality throughout an application without duplicating logic.</p><h4>Helpful links</h4><ul><li><a href="https://angular.io/guide/http#intercepting-requests-and-responses">Angular docs</a></li><li><a href="https://ng-interceptors.netlify.com/">Demo app</a></li><li><a href="https://github.com/schuchard/ng-interceptors">Github example</a></li></ul><p><em>Originally published at </em><a href="https://kevinschuchard.com/blog/2019-05-08-http-interceptor"><em>kevinschuchard.com</em></a><em> on May 8, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=337e1a26fd97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/3-ways-to-use-angular-http-interceptors-337e1a26fd97">3 ways to use Angular HTTP Interceptors</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why NOT going to conferences is costing you too much]]></title>
            <link>https://medium.com/briebug-blog/why-not-going-to-conferences-is-costing-you-too-much-9ba3de3a5efd?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ba3de3a5efd</guid>
            <category><![CDATA[conferences-in-usa]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jesse Sanders]]></dc:creator>
            <pubDate>Tue, 18 Jun 2019 17:17:03 GMT</pubDate>
            <atom:updated>2019-06-18T17:17:03.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmvN5x2Z73ZOlKaX1j9g5A.jpeg" /></figure><p>I have been a professional developer for over 20 years. I officially started learning to code on my TRS-80 Color Computer about 35 years ago. I grew up in a very rural area — Chimney Rock, CO — and there might have been 50 people in a 5 mile radius. Being in such a remote area, learning to code was difficult.</p><p>I distinctly remember getting 4 chapters into <a href="http://bit.ly/2wuXqJ4">Getting Started with Extended Color Basic</a>, and getting stuck because I couldn’t wrap my brain around for/next loops at age 13. I had no one to reach out to who could help me, so I put the book down and stopped my learning.</p><p>I repeated this 3 or 4 times over the course of a year until I could finally grasp the concepts and complete the book.</p><p>Fast forward 20 years to 2004 — I’d become a Visual Basic programmer. I learned new techniques and concepts by reading 800+ page books, while typing code examples in. This process of learning was effective, but took a lot of time to learn concepts. There was little feedback on best practices, and often the patterns I implemented struggled when the applications scaled. Learning was tough, often with outdated materials/books/articles, and the options were limited.</p><p>I almost never went to conferences or user groups/meetups over those 20+ years, as I didn’t see the value in it. I attended a few user group meetings in the early 2000’s before open source was really a thing, and developers rarely shared anything valuable at these meetings. It was mostly a quick show-and-tell, with no code examples or real explanation of techniques. Everything was coveted, and I would usually feel like I wasted my time at the event.</p><p>Over the past 4 years I have been a part of over 100 meetups and about 10 conferences all over the world including <a href="https://www.ng-conf.org/">ng-Conf,</a> <a href="https://angulardenver.com/">Angular Denver</a>, Angular U, ngIndia, Angular Mix, International JavaScript, <a href="https://angular-up.com/">Angular Up,</a> and Framework Summit. These conferences have become an invaluable learning resource for myself and my team, so much so, that I bring my entire development team to ng-Conf and Angular Denver every year so we can all learn about the new developments, techniques, best practices, and patterns going on in Angular. I couldn’t imagine not going to conferences and learning.</p><p>I organize the local Rocky Mountain Angular meetup here in Denver, and have for the past 4 years. I often emcee the local event to make announcements and introductions. When exciting conferences are coming up I ask for a show of hands on who is planning on attending. Even when conferences are right in their own backyard, a majority of developers don’t attend. When asked, the common answers boil down to “can’t afford it,” “my employer won’t pay for it,” “it costs too much,” and/or “I can’t get the time off work.”</p><p>It’s disappointing to me how little priority is placed on educating the workforce. As a Google Developer Expert in Angular and Web Technologies, I see firsthand how bad or outdated practices are costing businesses millions of dollars. I am often consulted on projects that fail to meet requirements, perform poorly, are riddled with bugs, or are outright cancelled, and almost always it is because developers haven’t been exposed to best practices or the proper way to develop projects.</p><p>So, whether you are a developer or in management, I would implore you to take another look at what you are doing for training. <strong>Conferences are one of the best ways for you to learn what is out there, what you should be learning, and the direction that the web is heading.</strong></p><blockquote>If you think conferences are too expensive, consider the cost of failed projects.</blockquote><p>If you’re still not convinced, check out <a href="https://angulardenver.com/">Angular Denver</a>. The ticket price is around $500 to see 45 speakers from around the world and workshops are 40% less than what you might pay for the same workshop at other conferences.</p><p>In closing, some might ask, “if everyone goes to conferences and learns the best practices, wouldn’t that put BrieBug out of business”? I think it’s a great question and maybe one day we will have to cross that bridge. In the mean time, we are currently working on online training courses via <a href="https://thinkster.io/">Thinkster.io</a>, as well as Angular Fundamentals 3-day training courses to help teams level up.</p><p>If you’ve found yourself struggling with a project, needing an architecture review, or wanting training with Angular Fundamentals or NgRx, please reach out to me to setup a time to talk.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ba3de3a5efd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/why-not-going-to-conferences-is-costing-you-too-much-9ba3de3a5efd">Why NOT going to conferences is costing you too much</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visual Testing with Cypress]]></title>
            <link>https://medium.com/briebug-blog/visual-testing-with-cypress-9a0b7443e427?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/9a0b7443e427</guid>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[visual-testing]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Jesse Sanders]]></dc:creator>
            <pubDate>Thu, 30 May 2019 14:59:22 GMT</pubDate>
            <atom:updated>2019-05-30T14:55:54.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*ywk6bLM3dQ61NK5p.jpg" /></figure><p>Testing is a very important part of the software development cycle and has become much easier than when I started out as a developer. The tools continue to improve and the techniques are far more sophisticated. We are able to write unit, integration, and end to end tests that quickly and thoroughly test our applications. No longer are we constrained by manual testing that requires large teams of testers to manually comb through the application to report bugs.</p><p>I recently gave a workshop talk on Cypress and how to use it for E2E testing. Cypress is a powerful tool with an intuitive interface that allows developers to debug tests step by step and see the state of the UI while inspecting elements, api payloads, etc. One of the toughest aspects of E2E testing is testing edge cases. Historically, this meant we would either need a seed database with the right data or our tests would need to create the data first before locating it in our test flow. This added to the time tests took to run and often contributed to the flakiness of our tests. Cypress allows us to stub our responses from the server, wait for responses, and reach every edge case with relative ease.</p><p>You can see the talk here: <a href="https://youtu.be/GH9Dvo_BYkk">https://youtu.be/GH9Dvo_BYkk</a></p><p>What about testing more visually complex elements? Historically, testing graphs or other complex elements was fairly limited. Tests would go to the page in the application where these elements were rendered and check for basic rendering and that no errors occurred. Since these type of elements often use application data to render, they can vary in each run and would be almost impossible to verify if they rendered correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*A4NWnP498myqBSGDMT7b4g.jpeg" /><figcaption>How would you write a test to validate this graph?</figcaption></figure><p>By using Cypress and utilizing stubs, we control the data being fed to our complex visual elements. If our components are deterministic they will render exactly the same way if given the same data. This opens the door to visual testing which has been around for a while, but has been limited in effectiveness due to the variance in data being returned from external sources.</p><p>Cypress by itself doesn’t have tools built in to do visual testing, but there are several options that make it simple to implement. The first option is a more manual process, but is free to use. This option is an npm library called cypress-visual-regression that uses the PixelMatch library to do image comparisons. This library is a cypress plugin that captures base images and then compares current images in subsequent test runs. If any of the images vary, an error is thrown and the differences can be inspected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*7igBCI40165DkVYE" /></figure><p>Once installed, some configuration is required. First we need to create a cypress.json file if it doesn’t already exist in our project. We need to tell cypress where the default screen shots folder is located and if we want to dispose of prior test run images (sans our baseline) when starting a new test run. Once we have this configured, we have to tell Cypress about our plugin. This involves editing the plugins/index.js file to tell Cypress about the plugin and then the commands file to add a new Cypress command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eq-W1_r7sln_Me5R" /></figure><p>Once we have our plugin configured, our tests look like regular Cypress tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*_mU6hu1nJlYy4KUG" /><figcaption>Cypress Visual Regression Test</figcaption></figure><p>In a real world test, we would likely stub the data being returned in the test so our element/page would render consistently. But, for the purpose of this article, we will write a simple test.</p><p>Once we have the tests, it’s time to create a baseline. Once we have a baseline, the second command is what we will use to compare if anything has changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FQ08Jtms00-Yp79l" /></figure><p>Cypress will kick off the tests, capture screenshots, and compare the current screenshot to the baseline. If anything is different, the test will fail, and we can inspect the images to see the baseline, actual, and difference. This is a manual process, which works well locally on a development machine, but can prove to be more difficult when utilizing a continuous integration server on the cloud.</p><p>If this last approach felt a little too manual and it left you feeling like you wished there was something more, then this section is for you. It’s great to have free tools that get us started, but in larger production environments it’s nice to have all the bells and whistles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*UMh3qeqRZrG7dYD2Fwc6OA.jpeg" /></figure><p>Percy.io is a cloud based visual testing tool that neatly integrates into Cypress and provides advanced features like workflow and git hooks. Installation is very easy with a simple npm install and then a single import line to integrate it into your tests. Add your Percy token to your environment and Percy takes care of the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/0*xAeAbixGd7NvWZbL" /><figcaption>Setup steps for Percy.io</figcaption></figure><p>There are a couple of intermediate steps which include creating an account with Percy.io, then creating a new project. Once you have a project created, you will need to copy your PERCY_TOKEN for the project and add it to your command line instance like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*8Sb9bFaPC1l9_7y-HWbcUw.png" /><figcaption>Add your Percy token and then execute the tests</figcaption></figure><p>Cypress will run your tests and everywhere there is a “cy.percySnapshot();” call, Percy will take a snapshot, upload it to the cloud, and compare the results to the baseline (if one exists, otherwise the new image will become the baseline). You can specify the screen widths to capture and Percy will do all the work to bundle your test run into a workflow for your approval</p><p>Any images that don’t match their base image will require a user to approve the changes. Any images that fail in the same exact way will be group together to make the approval process faster. Groupings can be expanded and the workflow process makes comparing the results very very easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZ9qVnmpTfqoNMTBFb9dmg.png" /></figure><p>In addition, Percy.io has GitHub hooks to integrate into your PR process to ensure that visual changes are approved before code is merged to the next branch. This approval process creates a solid code quality process when combined with code reviews, linting, unit tests, code coverage, and E2E testing.</p><p>If you’re ready to take your testing game to the next level, you should definitely consider visual testing with Cypress and Percy.io. These two products when combined together give us a new tool in our tool-belt to prevent random UI changes that would otherwise be easily missed by typical manual validation methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0b7443e427" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/visual-testing-with-cypress-9a0b7443e427">Visual Testing with Cypress</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing NgRx Auto-Entity]]></title>
            <link>https://medium.com/briebug-blog/introducing-ngrx-auto-entity-fdd755ce119b?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/fdd755ce119b</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[auto-entity]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[ngrx]]></category>
            <dc:creator><![CDATA[Jon Rista]]></dc:creator>
            <pubDate>Thu, 23 May 2019 17:42:00 GMT</pubDate>
            <atom:updated>2019-05-24T04:18:03.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsS1qhfu1mTDm_L8m4uA_g.jpeg" /></figure><p><strong>NgRx</strong>. Most Angular developers should be familiar with the term. It should invoke notions of state machines and modern architecture. NgRx has become largely fundamental to Angular development today, much like Redux became fundamental to React development. Here at BrieBug, we LOVE NgRx, as a concept and pattern, as well for its high level architecture.</p><p>Like recent opinions about Redux, NgRx may also evoke concurrent feelings of both love and hate, as there are indeed things to adore…and sometimes things to loath about the framework as it has been implemented thus far today. The terms “boilerplate” and “heavy code” and “tedium” may come to mind, as sadly these are some of the natural side-effects of NgRx due to its (purposeful) design.</p><p>So, what is <strong>NgRx Auto-Entity</strong>? Derived from “generic actions”, the brainchild of BrieBug CEO Jesse Sanders, and the pet project of several of us BrieBuggers for a number of months in our rare spare moments of free time. NgRx Auto-Entity is an add-on library that aims to address the heavier nature of NgRx, to eliminate the necessity of what has colloquially become termed “boilerplate” from what is otherwise a wonderful concept and solid design principal. In a nutshell: Defining Actions! (And handling them…)</p><p>NgRx Auto-Entity provides a set of ready-made generic entity <strong><em>actions</em></strong>, supporting standard CRUD operations as well as covering a few common NgRx usage patterns, along with a set of pre-made and fully encapsulated effects and reducers, that can be used to automate standard entity CRUD with NgRx.</p><p>NgRx Auto-Entity is fundamentally nothing different from the normal NgRx you are already familiar with, and we aim to support continued use of standard NgRx best practices…in the <em>occasions</em> they are absolutely necessary. Our goal is, ultimately, to make the great parts of NgRx <em>easy</em> and <em>pleasant</em> to use by offering ready-made solutions for the most frequent use cases (and the largest source of “boilerplate”), while still allowing complete and total flexibility and autonomy by the developer when necessary.</p><blockquote>This article aims to be a complete and thorough introduction. As such, it may be a little longer than your normal 5 minute read. I’ve attempted to break the article into logical sections, which may also serve as useful stopping points for those who may not wish to sit and read the whole thing at once.</blockquote><h3>The Problem</h3><p>When discussing NgRx with fellow colleagues and other Angular developers in the community, as well as when reading about NgRx in other articles around the Internet, the most common complaint is the sheer volume and dispersion of code necessary to define and create usable actions, create entity state, implement common reducer patterns, implement effects, etc.</p><p>NgRx requires a lot of repetition, especially around actions and all the bits and pieces and little parts that make an action a fully usable part of NgRx. While technically each individual action and each individual reducer case may be “unique” in the sense that they handle different distinct actions, we generally tend to write the same kind of code, the same exact patterns and structure of code, repeatedly with NgRx.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*342CWSlnzghf3CJ4r26fhw.gif" /></figure><h4>Other Solutions</h4><p>There are existing solutions to this necessity of repetitive code. Many of you may be familiar with Angular Schematics, which are a powerful and extensible CLI framework for generating source code and adding it to Angular projects. Code generators can take away a lot of the tedium involved in implementing NgRx.</p><p>All of the necessary code for each action, each entity reducer, and some of the code for effects can be created in about 30 seconds with a custom Angular schematic. In fact, BrieBug has provided our own library of schematics that do just this, and they are available <a href="https://www.npmjs.com/package/@briebug/ngrx-entity-schematic">here</a>! BrieBug’s ngrx-entity-schematics are designed to fill exactly this niche.</p><p>Another solution that has been around for a while are “snippets”, an add-on for VSCode (and perhaps other IDEs) that allows you to type in a simple short code that expands instantly into all of the necessary code for a new action, or a new reducer or effect. Snippets are great for adding new individual actions or for quickly <em>boilerplating</em> a non-entity reducer…but they have their limitations.</p><p>These two solutions address some of the tedium issues with NgRx. They take care of most of the need to manually write a lot of the code. That said…both solutions still leave you with a rather large volume of NgRx code in your code base. That code is also often still dispersed rather widely through your codebase. There are different schools of thought on just how necessary actually spelling out each and every action really is, and the exact value here may depend on the project and its scale.</p><p>For anyone who has worked on larger projects, or even for anyone who is itching for simpler, smaller, cleaner codebases, you may still find that this is not an ideal solution. State related code can add a fair amount to the overall size of your minified codebase and it adds to the size and complexity of your folder and file structure when writing code. Some larger projects may still end up with thousands of actions, nearly as many effects and hundreds of reducers.</p><h4>What about angular-ngrx-data?</h4><p>Another solution that is currently available is angular-ngrx-data (soon to be @ngrx/data). This library, created by John Papa and Ward Bell, is another attempt to greatly simplify NgRx usage and reduce the overall complexity of using a reactive state machine in your applications.</p><p>For some projects, angular-ngrx-data may be the most appropriate option. If your ultimate goal is to reduce the necessary code footprint to nearly zero, then this may be the library for you. This library takes more of a configuration-centric approach, allowing you to configure various aspects of the library and your entities. It is worth <a href="https://github.com/johnpapa/angular-ngrx-data">taking a look</a> to see if it fits your needs!</p><p>Our NgRx Auto-Entity library takes a different approach and tries to solve the same problem in a different way, one that is not “zero-effort”, is still very low-effort, yet also highly flexible, addressing a wider range of needs and still <strong><em>familiar and standardized</em></strong>. Rather than a configuration-centric approach, we take a functional and programmatic approach, and one that works with existing patterns and practices in the underlying NgRx and Angular frameworks rather than orthogonal to them.</p><h3>The Auto-Entity Solution</h3><p>Now enter <strong>NgRx Auto-Entity</strong>. The fundamental goal is to provide a set of ready-made, reusable common actions that may be dispatched for ANY entity, without the need to create a new set of action/effect/reducer (“boilerplate”) code (either manually or generated) every time you need to include different entity in state.</p><blockquote>When you wrap up your Product implementation and are ready to move onto Inventory, then Orders and LineItems, then Customers, etc. you can continue to reuse a single set of generic actions.</blockquote><p>NgRx Auto-Entity’s other goal is to minimize the amount of code required to initialize a new piece of state. You will no longer need to create any actions. You will not need to implement a reducer, nor will you need to manually configure an Entity Adapter. You will also not need to implement any effects.</p><p>The sole exceptions here are if you have a custom and unique need not addressed by our standard <strong>CRUD</strong> actions or companion actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yGwgt4DJD557I5gYWZ4Gdw.png" /></figure><p>To that end, if a custom action is required, for any reason, NgRx Auto-Entity is an add-on library. It in no way limits your ability to use NgRx the way you always have. If you have a custom need, and require the ability to implement your own actions, your own effects and your own reducers, you may do so at will. We aim <strong>not</strong> to be a barrier to accessing and leveraging the full low-level power that NgRx offers.</p><p>When NgRx Auto-Entity is present, we may still be able to help you reduce the amount of code you must implement, as many <em>initiating actions</em> may in turn dispatch Auto-Entity Success or Failure generic actions in order to integrate data retrieved with your own custom actions with Auto-Entity managed state. Flexibility is a fundamental tenant of NgRx Auto-Entity.</p><h3>Auto-Entity Architecture</h3><p>NgRx Auto-Entity (NgRx-AE for short) is an add-on library to NgRx. It is not an alternative to NgRx, it in fact is built on top of NgRx utilizing standard NgRx implementation patterns.</p><p>NgRx Auto-Entity aims to provide a more Angular-like (i.e. decorated) approach to entity state, a simpler, unified approach that requires minimal manual implementation on the developer’s part. General usage of NgRx Auto-Entity can generally follow the normal, familiar patterns you already use with NgRx.</p><p>Additionally, NgRx Auto-Entity also offers a more fully encapsulated usage pattern, facades, that we hope will simplify your usage of a reactive state machine even more!</p><h4>Our Actions</h4><p>At its core, NgRx Auto-Entity provides a set of ready-made standard CRUD actions, which cover the most common and prolific use cases for NgRx in general. We support a variety of means of Loading (GET) data, including individual entities and lists of entities, as well as loading pages or ranges of entities.</p><p>We also support your standard Create (PUT), Update (PATCH), Replace (PUT), and Delete (DELETE). Further we provide a set of actions for other common NgRx entity-related behaviors, such as Select, Deselect and Clear.</p><p>Utilizing our actions requires minimal change from what you are already familiar with when it comes to NgRx actions. Our actions are newed up the same way, with the additional requirement that the model type be passed in as the first argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a294c81d2c0bd585f00fb92e20a8a0a/href">https://medium.com/media/6a294c81d2c0bd585f00fb92e20a8a0a/href</a></iframe><p>In order to support all of the potential requirements when requesting entities, each generic “initiating” action also supports custom criteria as the last argument. This custom criteria is typed as any, thus allowing you the developer to pass whatever you so desire here. This custom criteria is then made available in your entity services to support any form of entity request you may require, to any kind of backend service, regardless of how custom or complex, or even if it is hosted in a standardized cloud service like FireBase.</p><h4>Effects and Reducers</h4><p>Auto-Entity ships with a set of ready-made, fully functional effects and reducers for entity state. You are no longer required to implement any effects at all, unless you find a need for a custom action. You must initially register our effects class with the NgRx Effects module, same as with any other effects class.</p><p>You are also not required to implement any reducers, again unless you find a need for a custom action. Auto-Entity handles all of it’s own entity reduction through a single, global meta-reducer. This meta reducer must be added to your list of meta reducers for your state, once that is done any Auto-Entity actions that are dispatched are reduced automatically.</p><p>A basic, “empty” reducer (stub reducer) is required for each entity state simply to support NgRx’s standard state and reducer map configuration and allow the reducer map to be used in the @NgModule decorator, however such reducers can be extremely minimal and bare-bones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5073836e21ce15e58cdb9d87864295a/href">https://medium.com/media/b5073836e21ce15e58cdb9d87864295a/href</a></iframe><p>You may note from the above, we have also eliminated the need for you to create a state interface. Any Auto-Entity state may leverage our IEntityState&lt;TModel&gt; interface which encapsulates all of the necessary data to fully support Auto-Entity’s internal meta-reducer.</p><p>Finally, you are also no longer required to manually configure initialState. Auto-Entity provides a basic utility function, buildState, that handles the creation of initial state as well as standard selectors for you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a606fdd1150082d1c751f2c8f128c15f/href">https://medium.com/media/a606fdd1150082d1c751f2c8f128c15f/href</a></iframe><p>Auto-Entity provides all of the standard selectors that are also provided by a normal NgRx/Entity adapter, as well as a number of additional selectors that facilitate other built-in features of Auto-Entity.</p><p>In fact, our buildState utility function will provide you with a lot of ready-made facilities, including the initialState, all necessary selectors to retrieve the state Auto-Entity manages, an initial starter reducer (same as the example above, all you need to do is export it with a unique name), as well as a <em>getter function </em>entityState to retrieve the entity state object that can be used in creating custom selectors.</p><p>You may also include additional initial state as the second parameter to the buildState utility function, which allows you to prepare additional initial state for custom effects and/or reduction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/373b133f023497b2f946e579b0241e50/href">https://medium.com/media/373b133f023497b2f946e579b0241e50/href</a></iframe><p>For more information about how to set up a project to use NgRx Auto-Entity, read our <a href="https://briebug.gitbook.io/ngrx-auto-entity/quick-start">Quick Start</a> documentation on GitBook. This will walk you through the few steps required to prepare your project to use this library and start automating your entity state.</p><h4>The Developer’s Responsibility</h4><p>Once you have set up your project to use NgRx Auto-Entity, there are two pieces of code that are still the full responsibility of the developer. These two aspects of any state are usually unique on a per-implementation basis, and cannot easily be “automated”. These include the <strong>entity model</strong> and the <strong>entity service</strong>. The developer is usually responsible for these two pieces of code regardless, however we hope that Auto-Entity may assist you here as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-t4mXIIezHF50yTRNlQwyw.png" /></figure><p><strong>The Model<br></strong>With Auto-Entity we must enforce one small change to your classic entity models. Rather than implementing them as interfaces they must be implemented as classes instead. This is necessary, as NgRx Auto-Entity requires runtime type information in order to work its magic.</p><blockquote>An interface is a compile-time only construct within the context of TypeScript, while a class is, pardon the pun, a “first class citizen” of native ECMAScript.</blockquote><p>Defining a model is as simple as ever, with one additional requirement above and beyond replacing interface with class. Auto-Entity aims to make entity state more Angular-like by using decorators where they seem appropriate. One such case is specifying the key of your entity types:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da77001525ea13ff17c3aeac77e020d4/href">https://medium.com/media/da77001525ea13ff17c3aeac77e020d4/href</a></iframe><p>Note the @Key decorator here. This simple decorator marks the id property of the Customer model here as the entity key. NgRx Auto-Entity will then utilize this metadata within our standard side effects and meta-reducers to support proper reduction of entities. In the event that an entity has a composite key, Auto-Entity supports that as well…simply decorate all properties of the model with @Key and the library takes care of the rest.</p><blockquote>NOTE: Auto-Entity provides a number of utility functions to support your development of applications with the library. This includes a getKeyFromModel function that may be used to retrieve the entity key of any entity from its model type.</blockquote><p><strong>The Entity Service<br></strong>The next piece of code that is still the responsibility of the developer is the entity service. These are classically standard Angular services, however with Auto-Entity we add the additional requirement that our IAutoEntityService&lt;TModel&gt; interface be implemented. This interface ensures that your entity services provide the necessary functionality for NgRx Auto-Entity to properly interact with them. Further, we also require that entity services be provided within Angular’s providers in a very explicit manner:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65dd07899474286d082fd784a2daeeda/href">https://medium.com/media/65dd07899474286d082fd784a2daeeda/href</a></iframe><p>Auto-Entity leverages a useful aspect of Angular’s built-in injector and provider model: <em>The ability to map a custom implementation for a given provider type.</em></p><p>In our case, we require that the entity Model type be specified as the provider, and mapped to a useClass style implementation provided by your entity service. This is necessary, as at runtime the only piece of information NgRx Auto-Entity has initially to <strong>dynamically</strong> find the appropriate service to invoke to handle entity requests for a given model <em>is</em> the model itself.</p><p>Implementing an entity service is fairly straight forward. We specify a range of possible functions that may be implemented on our IAutoEntityService interface, however all of them are marked as optional. This allows you to implement what is necessary to support the various actions to require for each entity, without requiring that you boilerplate unnecessary code.</p><blockquote>The IAutoEntityService interface is then more of a guide to implementation than enforcing a specific implementation.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/708592d8d58d35072ad06dcc76f353a0/href">https://medium.com/media/708592d8d58d35072ad06dcc76f353a0/href</a></iframe><p>There are many additional methods that may be implemented. Each method provides a standard set of parameters, including the IEntityInfo metadata that describes your entity, the entity itself or its keys, as well as custom criteria that may be passed with any Auto-Entity action. Custom criteria supports complex entity requests, such as those that may require knowledge of parent keys, related keys, etc.</p><p><strong>Shared Entity Services<br></strong>One of our primary tenants with NgRx Auto-Entity is to support the smallest codebase possible whenever possible. While implementing an entity service is still the responsibility of the developer, we attempt to support simple architectures as well as complex ones. If you have a very basic entity API that follows explicit, common patterns for all entities, a single entity service may be used to handle all entity requests to your API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d58bdd18563fc117b04c34edd2e4d96e/href">https://medium.com/media/d58bdd18563fc117b04c34edd2e4d96e/href</a></iframe><p>This single entity service may then be mapped to multiple entity model providers as necessary:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/127fbe3ca0d61930ebbc67f3f9d9442e/href">https://medium.com/media/127fbe3ca0d61930ebbc67f3f9d9442e/href</a></iframe><p>You may find additional information about how to use and implement entity services in our <a href="https://briebug.gitbook.io/ngrx-auto-entity/">GitBook documentation</a>.</p><h4>Entity Façades</h4><p>True to tradition, we save the best for last! <strong><em>Façades!</em></strong> You may have encountered this term while trawling the Internet for NgRx articles. This is a pattern we at BrieBug have been embracing with open arms, and we wish to bring the wonder and simplicity of state façades to the masses with NgRx Auto-Entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bYVWuUGYz3c8uHpOD4YKgw.png" /></figure><p>A façade by definition is:</p><blockquote>An object that provides a simplified interface to a larger body of code, such as a class library.</blockquote><p>In combination with NgRx, a façade presents a simpler interface into the complexity of using the store, dispatching actions, and observing selectors. Façades are a great way to pull out a lot of the additional code and complexity involved with interacting with NgRx from your components. Façades encapsulate and isolate store interactions, allowing them to be more easily used, and shared, by one…or many…components in your UI.</p><p>NgRx Auto-Entity, with it’s latest beta version v0.1.0, now integrates support for prefabricated façade base classes. A facade base class is generated when you call buildState. You may destructure this class from the tuple returned, and rename it to a proper class name at the same time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df9cf2bce577ecbe608199fcc8fe4762/href">https://medium.com/media/df9cf2bce577ecbe608199fcc8fe4762/href</a></iframe><p>Once you have exported the façade with a unique type name, you may then implement your own façade class by extending it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/530fc69e5f0a9a48cb4ff204f454fc96/href">https://medium.com/media/530fc69e5f0a9a48cb4ff204f454fc96/href</a></iframe><p>This approach, of generating a base façade class that then must be extended, is required due to some of the limitations in how Angular works. Notably…we need to inject the store, but also need to specify the model type. Technically speaking, it should be possible to create a custom provider using a factory for the façade type returned by buildState, however doing so is a little odd, and can get a little messy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68c7345ab2395ae3e700bac3b607d03c/href">https://medium.com/media/68c7345ab2395ae3e700bac3b607d03c/href</a></iframe><p>Now imagine creating a new factory for <em>each and every</em> façade type, and registering each one, or perhaps creating a more complex factory to support multiple façade classes by model type. While possible, we prefer the child class/extension approach, as this offers the developer the <em>option</em> to add their own code to the façade, thus <em>extending</em> the API and encapsulating more reusable functionality.</p><p><strong>Entity Façades in Practice<br></strong>With façades, using Auto-Entity in your components becomes even easier than ever! You no longer need to worry about the store, selectors, dispatching, or any of the things you normally have to deal with when it comes to bringing app state into your components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a807a20ede4ccc9165b1e55bd23c91e/href">https://medium.com/media/1a807a20ede4ccc9165b1e55bd23c91e/href</a></iframe><p>Clean. Simple. Elegant! Fully encapsulated state management, without the complexities of selecting and dispatching. The code describes itself without effort. Façades provide a higher level, logical &amp; simplified API in front of NgRx state management. They are also very easy to extend. Let’s say we wanted to further simplify the logic in the onSave method above, so we can simply call customerFacade.save(customer). All we need to do is add a new method to our CustomerFacade class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a40cc4ada4a12afd7d104d450252297/href">https://medium.com/media/6a40cc4ada4a12afd7d104d450252297/href</a></iframe><p>Our onSave method can now be reduced to this simple beauty:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d968cf21681f1d05c34c4316f61d29ed/href">https://medium.com/media/d968cf21681f1d05c34c4316f61d29ed/href</a></iframe><p>We here at BrieBug encourage you to explore the power, simplicity and cohesive benefits of using façades in your Angular/NgRx applications. We also encourage you to leverage the prefabricated façade base classes generated by NgRx Auto-Entity to help jump start your exploration of these wonderful types and all the benefits they can offer.</p><h3>Extra Goodies</h3><p>Our library doesn&#39;t stop at just providing a core set of CRUD actions. In fact, we aim to automate <strong>all</strong> of the more common NgRx patterns for entity related state. This includes supporting things like selection of individual entities, clearing of entity state, as well as support for loading discrete pages or continuous ranges of entities. We also provide a wide range of standard selectors that provide temporal feedback about the ongoing state of a given action.</p><p>As a quick example, whenever a Load, Create/Update/Replace or Delete related action is issued, we maintain <em>isLoading</em>/<em>isSaving</em>/<em>isDeleted</em> state as well as <em>loadedAt</em>/<em>savedAt</em>/<em>deletedAt</em> timestamps. We also provide a range of ready-made selectors so that you the developer may observe this state at any time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*F18KxuuHy2ph-PwwcjKVBg.png" /></figure><p>Auto-Entity includes intrinsic support for the loading and proper state management of both pages or continuous ranges of entities, as well as loading data to replace the entities already in state, or augment (merge into) entities already in state.</p><p>Loading a <strong>page</strong> of entities will, by design, always replace <em>in state</em> any previous set of entities for the given model with the entities of the loaded page. This is intended to support literal paged display of large (or potentially massive) lists of entities from a large database.</p><p>In contrast, loading a <strong>range</strong> of entities will simply append <em>in state</em> any additional ranges of entities to those already loaded into state. This is intended to support things like <em>“infinite scrolling”</em>, a popular pattern for dealing with large continuous data sets these days on both phones and desktop browsers.</p><p>Another feature of Auto-Entity is the ability to selectively choose which effects are actually applied. As part of our goals of providing the end developer as much flexibility as possible, we provide a number of different classes containing different sets of effects, giving you the developer control.</p><p>You may include all effects for all types of generic actions, or you may choose to include only the effects for loads and manually implement CUD actions yourself. You may selectively include any set of actions for any subset of generic actions if you so desire.</p><h3>Future Goals</h3><p>NgRx Auto-Entity is an evolving library, as well as an evolving concept. Many common usage patterns exist within the scope of utilizing NgRx to store entity state.</p><p>A long-term goal we here at BrieBug have for this library is to expand it to support more of these common usage patterns. This may occur as additions to the core NgRx Auto-Entity library, or potentially as companion libraries that may be selectively added to your project to support one<br>or more new features.</p><p>Ideas that we are currently tossing around include decorator-guided automatic Loading, Saving, and Deleting <em>toasts</em> or <em>snackbars</em>. Complete with proper and automatic integration with the UI component library of your choice.</p><p>Other potentials include prefabbed shared entity service implementations for flat APIs as well as hierarchical APIs. Improved control over just how the automatic effects handle the generic actions you dispatch (notably, which mapping operator is used, as we believe there <strong>is</strong> a <em>time and a place</em> for <strong>all</strong> of them: switchMap, exhaustMap, concatMap, flatMap/mergeMap).</p><h3>Join Us!</h3><p>We invite you to give <strong>NgRx Auto-Entity</strong> a try today! While this is currently considered a beta library, a lot of effort has gone into designing a cohesive architecture and API. The library has been tested with several actual real-world projects here at BrieBug for the last several months, and has been fairly thoroughly debugged. That said, it is still an early-stage library, and if you encounter any issues please let us know on our <a href="https://github.com/briebug/ngrx-auto-entity">GitHub repository</a>.</p><p>You may install NGRX-Auto-Entity at the command line:</p><pre>npm install @briebug/ngrx-auto-entity<br>yarn add @briebug/ngrx-auto-entity</pre><p>Thanks for reading! We look forward to simplifying your life as an NgRx developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdd755ce119b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/introducing-ngrx-auto-entity-fdd755ce119b">Introducing NgRx Auto-Entity</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I’m not ready for NgRx]]></title>
            <link>https://medium.com/briebug-blog/im-not-ready-for-ngrx-2db4a96c1dd4?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/2db4a96c1dd4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Jesse Sanders]]></dc:creator>
            <pubDate>Thu, 23 May 2019 17:20:47 GMT</pubDate>
            <atom:updated>2019-05-23T17:15:00.958Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular has come a long ways since I started using it back in 2013. The days of “$scope” and massive views/controllers have been replaced with component based architectures and more elegant patterns. One of the more popular patterns over the past year or so is NgRx. For every supporter of NgRx there seems to be one in complete disagreement and another that doesn’t care. I hear a lot of chatter about whether or not a project really needs NgRx, and I’m going to say that if you’re not sure, then you probably don’t need it.</p><p>But, what if your project grows and one day needs a little more structure? One day you might want to implement NgRx into your project as the complexity grows, so a good strategy up front could save you from a massive rewrite later.</p><p>One alternative solution that gets thrown around a bit is <strong>service with a subject</strong>, but after scouring the web, it can be tough to find good examples of how to implement it. The first question that comes to mind is, “if this is such a good solution, why aren’t more people talking about it”? I asked this question myself and starting digging around to find out what all the hype is about.</p><p>Service with a subject is a simple pattern that when applied correctly gives developers a clear path to upgrading to NgRx (or similar redux pattern) with little to no refactor necessary. The basic premise is that each service with have a public behavior subject that will get set to the observable stream returned by our service calls.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51de8286a8f17fa0ca0bbbbf33d58011/href">https://medium.com/media/51de8286a8f17fa0ca0bbbbf33d58011/href</a></iframe><p>The biggest change here is when you call the user’s service “getAll function”, you no longer get a reference to the observable returned by the http call. Instead, the behavior subject (an observable stream) gets a new value added to the stream. This allows multiple components to share the same data and not be concerned with how the data is being updated. We protect the behavior subject by making it private and exposing a read only property that returns just the observable stream and prevents others from tampering with the stream directly.</p><p>Why do we use a behavior subject? Why not a regular subject? This is a great question and may not be obvious to everyone. If we used a regular subject class, it would still function almost exactly the same, but we may begin to notice how some components get the updated data where others don’t. This is because a regular subject will return values since you subscribed, but doesn’t hold onto the last value. Behavior subjects can have an initial value and return the last value, regardless of when subscribed to.</p><p>So now that you understand the basic premise of what service with a subject is about, we are ready to see how it all gets implemented.</p><p>If you’re not already using the container/presenter pattern, it’s one of the core patterns for modern web development. It doesn’t matter if you call it smart and dumb components or container and presenter components; it’s the same exact concept. If you aren’t familiar, I’ll be writing an article on it in the coming days.</p><p>The quick overview is that container components are typically your top level pages (not always) that are concerned with how things work. They are responsible for loading data, passing it to children components, and handling events as they bubble back up. Presentation components are just concerned with making the page look pretty. They receive data from a parent without knowledge of where it comes from, display that data, and emit events up to the parent for all user and system interactions. Presentation components have no business logic so that they can maximize reusability.</p><p>The container component will be responsible for calling the user service to get the data. In the example below, the “user$” variable is an observable stream of user objects that is set to our user service behavior subject. Anytime the behavior subject receives a new value, the container component will also receive that value without needing to be notified. On the initialization of the container component, the user service “getAll” method is called and the behavior subject will get a new value when the call completes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54cc7308d5fbe3ce225dac248424363e/href">https://medium.com/media/54cc7308d5fbe3ce225dac248424363e/href</a></iframe><p>The container component passes the data to the presentation component using the async pipe as illustrated in the example below. By using the async pipe, there is no need for a subscription to the observable stream. The presentation component will re-render when the stream receives a new value automatically and without expensive change detection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f60d51d190fab69a89c1049f74083b37/href">https://medium.com/media/f60d51d190fab69a89c1049f74083b37/href</a></iframe><p>The presentation component receives the data as an array of user objects and has no knowledge of the observable stream or how the data was obtained. Because the data received is from the container component is always new data and immutable, the change detection strategy can be set to “onPush” and gain the performance benefits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee10ebba32304b1394c78b84f6b01e3b/href">https://medium.com/media/ee10ebba32304b1394c78b84f6b01e3b/href</a></iframe><p>As you can see, the service with a subject pattern is very simple. Our controller components can request data on initialization and share that data with child presentation components via the async pipe. If an event causes the data to be updated, all of the presentation components will automatically be updated and without paying the price of change detection. You will also reap the benefits of using the container/presenter pattern to create components void of heavy business logic, simple to test, and maximize their reusablily.</p><p>If you want to update this component to use NgRx, you have two simple options. You can replace the service calls with calls to the store or you can apply the facade pattern for the service make calls to the store. My friend <a href="https://medium.com/u/9a50cd4fa96b">Thomas Burleson</a> wrote a <a href="https://medium.com/@thomasburleson_11450/ngrx-facades-better-state-management-82a04b9a1e39">great article on the topic</a>. If you choose to use the facade pattern it would allow you to upgrade to NgRx without having to make modifications to your components.</p><p>Check out this sample repo for a full working version:</p><p><a href="https://stackblitz.com/github/briebug/service-with-subject">StackBlitz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db4a96c1dd4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/im-not-ready-for-ngrx-2db4a96c1dd4">I’m not ready for NgRx</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Use of WebSockets in Angular — Way Easier Than You Expected]]></title>
            <link>https://medium.com/briebug-blog/making-use-of-websockets-in-angular-way-easier-than-you-expected-25dd0061db1d?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/25dd0061db1d</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Jamie Perkins]]></dc:creator>
            <pubDate>Thu, 16 May 2019 18:07:20 GMT</pubDate>
            <atom:updated>2021-02-03T17:53:00.429Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making Use of WebSockets in Angular — Way Easier Than You Expected</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DlTgMe5CZ5BfICp6i42f-g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/40XgDxBfYXM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jordan Harrison</a> on <a href="https://unsplash.com/search/photos/server?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Using WebSockets may seem daunting, but they are delightfully simple. And what you’ll be really glad to know, is that RxJs ships with a thin wrapper around the native browser WebSocket client. No additional third party dependencies are needed, and you get an observable data stream right out of the box!</p><p><strong>This article has moved</strong>: <a href="https://blog.briebug.com/blog/making-use-of-websockets-in-angular">https://blog.briebug.com/blog/making-use-of-websockets-in-angular</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25dd0061db1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/making-use-of-websockets-in-angular-way-easier-than-you-expected-25dd0061db1d">Making Use of WebSockets in Angular — Way Easier Than You Expected</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Implementing Drag and Drop in a Material tree]]></title>
            <link>https://medium.com/briebug-blog/angular-implementing-drag-and-drop-in-a-material-tree-f96b9fe40f81?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/f96b9fe40f81</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jamie Perkins]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 16:11:46 GMT</pubDate>
            <atom:updated>2021-02-03T17:51:54.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular: How to Implement Drag and Drop in a Material tree</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3eXe0uv9l4jetGXcP2e4YQ.gif" /></figure><p>The Material CDK released Drag and Drop in version 7, and it offers a powerful api for supporting drag and drop in your Angular app! The Material Tree is also a recent addition to Material, and it makes it possible to display structured data like a file explorer.</p><p><strong>This article has moved</strong>: <a href="https://blog.briebug.com/blog/angular-how-to-implement-drag-and-drop-in-a-material-tree">https://blog.briebug.com/blog/angular-how-to-implement-drag-and-drop-in-a-material-tree</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96b9fe40f81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/angular-implementing-drag-and-drop-in-a-material-tree-f96b9fe40f81">Angular: Implementing Drag and Drop in a Material tree</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jest Testing: Your test tools are all wrong!]]></title>
            <link>https://medium.com/briebug-blog/jest-testing-your-test-tools-are-all-wrong-6bdbcdf56f0?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/6bdbcdf56f0</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[BrieBug]]></dc:creator>
            <pubDate>Thu, 14 Mar 2019 20:03:31 GMT</pubDate>
            <atom:updated>2019-03-14T20:01:23.149Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Written by </em><a href="https://medium.com/@jesse.sanders"><em>Jesse Sanders</em></a><em>, CEO, BrieBug</em></p><p>I LOVE TESTING.</p><p>Everyone loves the excitement of a new project. There is planning to do, new technology to work with, and the green field of possibilities gets everyone excited.</p><h3>The Start</h3><p>We all agree that with this new project that we are going to do things right. We set lofty goals around test driven development (TDD) and 100% code coverage while we develop our testing strategy. As the project kicks off, we slowly have to let go of TDD and pair programming to meet a few deadlines and before we know it, tests are falling behind to meet the stringent deadlines coming down from management.</p><blockquote><em>Reality begins to sink in… I LOVE the IDEA of testing, especially you testing YOUR code. Mine is probably fine.</em></blockquote><p>The reality is that testing is hard. Testing takes a lot of time. As we write unit tests, we begin writing code to mock out our backend services and before we know it, the mocks feel like they have a life of their own warranting a separate project. As developers, we become frustrated with the entire process and begin to do the minimum shallow tests to squeak through a code review. Then, as we begin to refactor our code to improve it, a massive number of tests begin to fail and it requires hours of combing through tests and mocks to figure out what changed and why everything is failing. To make matters worse, the tests take a long time to run, and on each iteration we have to execute the entire suite of tests to get to the test we are trying to fix.</p><p>Discouraged developers face a grim reality, either comment out the failing tests to meet the deadline, or spend the evening/weekend working through the massive list of failures.</p><h3>Jest: A Better Way</h3><p>There has to be a better way…</p><p>Jest might just be the testing tool you’ve been waiting for. It was created by the Facebook team in order to to improve the testing process. It was originally created in 2015, but wasn’t received well, even at Facebook. It was difficult to configure, confusing, and not intuitive. In 2017 a new version was released that promised zero configuration and an easy to learn syntax.</p><p>The features of Jest are impressive. It’s super fast as it uses JSDOM, a JavaScript implementation of web standards suitable for testing, and doesn’t have the overhead of a traditional browser. Each test is sandboxed as to not affect other tests. This leads to more reliable testing. The error reporting is a huge improvement over other test runners like Karma. No more having to dig through stack traces to figure out which tests failed and why. Jest offers zero config for JavaScript applications, which makes setup a synch. The feature that separates Jest from the pack, though, is snapshot testing that allows the developer to focus on writing tests, not mocks.</p><h3>Reporting</h3><p>The test output is a lot more readable and understandable using Jest. The challenge with using other tools like Karma is having to dig through very large stack traces trying to locate the test(s) that failed, and why. The test output for Jest is very readable and makes finding errors a breeze.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pPSlmUSJYbiZCXxG" /></figure><h3>Code Coverage</h3><p>Another great feature about Jest is that code coverage is built in and easy to use. Developers save time as the output is inline and not in an html file that needs to be opened/refreshed after every run. Further, the code coverage output can be piped through istanbul or other similar filters to comply with various CI tooling. Running tests with coverage is as simple as `jest — coverage`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YBWN9L-1ZnPPhCSn" /></figure><h3>Jest CLI</h3><p>Jest has several CLI features that make running tests even easier. Jest has a powerful CLI file matching feature to execute only the tests that you need to. For example, say I only want to run tests with the name customer in the filename. I can execute `jest customer` and only those files matching the string “customer” will be selected for testing. In addition, jest has a watch mode that extends this filtering even further while providing several other powerful tools. It’s as simple as executing `jest — watch`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QWBWQBW6nRaqGTE0" /></figure><p>From the watch interface, a developer can run all tests, just failed tests, filter test by filename using a regex, and filter tests by test name using a regex. This make focusing on just failing tests or specific tests in a functional area very easy. No more waiting for all the passing tests to run before getting to the failed tests. Focus on what is important.</p><h3>Migrating to Jest</h3><p>One big concern developers have about bringing in a new testing framework is having to learn a whole new setup and syntax. If you’ve been using Karma and Jasmine in your test suite, which is the default for an Angular CLI project, then Jest will be very familiar. The Jest testing globals are based on Jasmine globals, so for most developers, it looks exactly the same. In addition, there is little to no need to refactor existing tests to work with Jest because they work as is.</p><h3>Snapshot Testing</h3><p>The biggest difference between Jest and other testing frameworks is snapshot testing. Snapshots allow you to capture a “snapshot” of serializable values and compare them to previous values. This simplifies how we write our tests and allows us to analyze how state has changed over time. The serializable values can include JSON objects, HTML, or text, to name a few. Snapshot testing compares the expectation to a stored snapshot and creates a snapshot if one doesn’t already exist. It performs a diff comparison on the snapshot and produces an output similar to a git diff. The snapshots are stored in a <em>__snapshots</em> folder and the files become part of the code review process.</p><p>You might be asking, what are the benefits of using snapshots? The biggest reason is our mocks can be minimal or even elimited. You don’t have to create and maintain complex JSON objects to compare our unit test results to. Imagine storing the expected result of your unit test and receiving a warning anytime it changes. The same can be done for HTML. Since component views should be deterministic, e.g., if given the same inputs, they should produce the same output each time, then we can simplify our component tests and get better coverage by using snapshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OHY7JDxcEeukTNWE" /></figure><p>Jest and snapshot testing is here to change how we think about tests, and reduces the amount of time it takes to deliver quality tests. Updating and fixing tests after refactors becomes much easier, and developers begin to enjoy writing tests. Take Jest for a spin and see if you don’t agree.</p><p>You can reach me at:</p><p>Email: <a href="/service/mailto:jesse.sanders@briebug.com">jesse.sanders@briebug.com<br></a>Follow me on Twitter: @JesseS_BrieBug</p><p>References<br>To learn more about marbles and the supported syntax, checkout:<br> <a href="https://github.com/ReactiveX/rxjs/blob/master/doc/marble-testing.md">https://github.com/ReactiveX/rxjs/blob/master/doc/marble-testing.md</a></p><p>Check out the GitHub repo for this blog:<br><a href="https://github.com/briebug/ngrx-jest-testing">https://github.com/briebug/ngrx-jest-testing</a></p><p>Check out my talk at ng-Conf on NgRx Jest Testing:<br><a href="https://www.youtube.com/watch?v=d91uDEmbBUs">https://www.youtube.com/watch?v=d91uDEmbBUs</a></p><p>Slides from my talk:<br><a href="http://briebug.github.io/presentations/ng-meetup/2018/02/ngrx-jest-testing">http://briebug.github.io/presentations/ng-meetup/2018/02/ngrx-jest-testing</a></p><p><em>Originally published at </em><a href="https://blog.briebug.com/jest-testing-your-test-tools-are-all-wrong"><em>blog.briebug.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bdbcdf56f0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/jest-testing-your-test-tools-are-all-wrong-6bdbcdf56f0">Jest Testing: Your test tools are all wrong!</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common Angular Errors And How To Fix Them]]></title>
            <link>https://medium.com/briebug-blog/common-angular-errors-and-how-to-fix-them-f40d5f2e75ef?source=rss----a8a798084f9e---4</link>
            <guid isPermaLink="false">https://medium.com/p/f40d5f2e75ef</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jamie Perkins]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 15:44:44 GMT</pubDate>
            <atom:updated>2019-07-19T13:11:20.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NookfAYb9_HDtjBoNMSwpw.jpeg" /></figure><p>Angular is such an awesome framework, but sometimes the errors leave you guessing. Have you ever wished that you had a cheat-sheet for fixing errors in Angular? Well, now you do. This article covers the most common Angular errors, their most common causes, and how to fix them.</p><p>This article will be divided into sections for each error. Search the text of your error, or settle in for some light error reading. 😉</p><blockquote><strong>Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked</strong></blockquote><p>Here is the most infamous of Angular errors. There are a variety of causes and fixes, but here’s the <strong><em>silver bullet </em></strong>fix: Use the OnPush change detection strategy. In a root component, AppComponent if you’d like, specify your change detection strategy:</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export <em>class</em> AppComponent {</pre><p>Every child component will inherit this change detection strategy. It will completely eliminate the error but there’s a caveat: every binding must be immutable. That means you can’t mutate the same property, you have to set it to something entirely new in order to trigger change detection.</p><p>If you don’t want to implement On-push, here are common causes of the error and how to fix it:</p><ul><li>A property you are binding to was undefined or null and then had a value set at runtime. Solution: set default value.</li><li>Sometimes this error occurs because you are using the async pipe with synchronous code, such as calling next() on a BehaviorSubject. Here are several ways to make your code asynchronous: Use a setTimeout, or pipe delay(0) on your observable:</li></ul><pre>setTimeout(() =&gt; this.mySubject$.next(true));<br>// or...<br>this.mySubject$.pipe(delay(0));<br>...<br>this.mySubject$.next(true);</pre><blockquote><strong>Error: Template parse errors:<br>Can’t bind to ‘formControl’ since it isn’t a known property of ‘input’.</strong></blockquote><ul><li>You need to add ReactiveFormsModule to the imports of the module your component belongs to.</li></ul><blockquote><strong>Error: Template parse errors:<br>Unexpected character “EOF” (Do you have an unescaped “{“ in your template?</strong></blockquote><ul><li>Your template is likely missing a double-quote (“) or perhaps has an extra double-quote.</li><li>Your template has invalid interpolation — Where you should have {{ }} you might be missing a curly bracket.</li></ul><blockquote><strong>Error: No value accessor for form control with name: ‘foo’</strong></blockquote><ul><li>You added a formControl or formControlName binding to an element that isn’t an input, select or textarea. Reactive form controls <em>can only</em> be bound to valid form controls.</li></ul><blockquote><strong>Error: Template parse errors: Can’t bind to ‘foo’ since it isn’t a known property of ‘element’</strong></blockquote><ul><li>If it’s a directive selector, omit brackets unless it’s holding a value</li><li>If you’re seeing this error on a component, skip down to the next error</li></ul><p>Otherwise, you might be trying to bind to a native HTML element <em>attribute</em>. Maybe you tried something like this:</p><pre>&lt;a href=”test” [alt]=”myProp”&gt;Hi&lt;/a&gt;</pre><p>The proper way to do this is to prefix native attributes with “attr” like so:</p><pre>&lt;a href=”test” [attr.alt]=”myProp”&gt;Hi&lt;/a&gt;</pre><blockquote><strong>Error: Template parse errors: Can’t bind to ‘foo’ since it isn’t a known property of ‘foo-component’…</strong></blockquote><p>This could be because you simply forgot to add the @Input to FooComponent:</p><pre>@Input() someProp: any;</pre><p>Or it could be caused by the same issue that would cause this error:</p><blockquote><strong>Error: Template parse errors: ‘foo-component’ is not a known element</strong></blockquote><p>If FooComponent isn’t declared in any module yet, declare it in the module you are using it in:</p><pre>@NgModule({<br>  declarations: [ FooComponent ]<br>  ...</pre><p>If FooComponent comes from another module, say ModuleB, and you are trying to use it in a component that belongs to ModuleA, simply import ModuleB in ModuleA:</p><pre>@NgModule({<br>  imports: [ ModuleB ]<br>  ...<br>})<br>export class ModuleA {}</pre><p>And make sure ModuleB both <strong>declares <em>and</em> exports</strong> FooComponent:</p><pre>@NgModule({<br>  declarations: [ FooComponent ],<br>  exports: [ FooComponent ]<br>  ...<br>})<br>export class ModuleB {}</pre><p>If you are trying to use FooComponent in a lazy-loaded module you might have already imported its module, ModuleB in AppModule. That’s ok, you can import ModuleB again in the lazy-loaded module.</p><p>But if any modules included in ModuleB can only be in included once, you might see this error:</p><blockquote><strong>ModuleB is already loaded. Import it in the AppModule only.</strong></blockquote><p>In this case, find the module imported in ModuleB which exports FooComponent. Let’s call it ModuleC. Then just import ModuleC in your lazy-loaded module.</p><blockquote><strong>NullInjectorError: No provider for FooService!</strong></blockquote><p>This error can also happen for pipes. For both services and pipes, this error can be easily fixed by amending the decorator of your service, or including this additional decorator on your pipe:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})</pre><p>This will include the service or pipe in your root bundle. If the service isn’t required on the initial page load, you can avoid bloating your bundle by omitting the providedIn value, and instead just providing the service or pipe in the modules that need it by including it in the providers array:</p><pre>@NgModule({<br>  ...<br>  providers: [ FooService, FooPipe ]<br>  ...<br>})</pre><blockquote><strong>RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.</strong></blockquote><p>If this isn’t caused by actually calling RouterModule.forRoot() twice (once in the AppModule, and once in another module), then this is almost always caused by importing the AppModule. You never import the AppModule. It’s the root module that bootstraps your application.</p><p>Everything included in AppModule is already available to other modules. <em>However</em>, in a lazy-loaded module, you will need to re-import things that are already imported in AppModule. This is totally fine.</p><blockquote><strong>Error: Template parse errors: No provider for ControlContainer (“[ERROR -&gt;]&lt;form&gt;</strong></blockquote><p>If you’re using a form tag in a template, and you <em>are not </em>using a FormGroup, it will cause this error. Import the FormsModule to make it go away, or alternatively, use a FormGroup binding on your form tag, and import the ReactiveFormsModule.</p><blockquote><strong>Error: ngIfElse must be a TemplateRef, but received ‘[object HTMLDivElement]’.</strong></blockquote><p>You may have tried this:</p><pre>&lt;div #showLoading&gt;&lt;app-spinner&gt;&lt;/app-spinner&gt;&lt;/div&gt;</pre><p>But you need to use ng-template like so:</p><pre>&lt;ng-template #showLoading&gt;&lt;app-spinner&gt;&lt;/app-spinner&gt;&lt;/ng-template&gt;</pre><blockquote>Error: Uncaught (in promise): EmptyError: no elements in sequence</blockquote><p>This is an RxJs error. It can occur if you used first() in an Observable that had a takeUntil()emit before first().</p><p>I hope this has helped you discover the cause of your error and how to fix it. If so, please give some claps! If I left anything out, feel free to respond in the comments, and I’ll add it on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f40d5f2e75ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/briebug-blog/common-angular-errors-and-how-to-fix-them-f40d5f2e75ef">Common Angular Errors And How To Fix Them</a> was originally published in <a href="https://medium.com/briebug-blog">BrieBug Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>