<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fabian Beyerlein on Medium]]></title>
        <description><![CDATA[Stories by Fabian Beyerlein on Medium]]></description>
        <link>https://medium.com/@beyerleinf?source=rss-a186fda9ed3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9PGNZk5uXbrZJzwo6jLzmQ.png</url>
            <title>Stories by Fabian Beyerlein on Medium</title>
            <link>https://medium.com/@beyerleinf?source=rss-a186fda9ed3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:28:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@beyerleinf/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Azure Functions + esbuild = ]]></title>
            <link>https://medium.com/@beyerleinf/azure-functions-esbuild-3773ea5b8a62?source=rss-a186fda9ed3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3773ea5b8a62</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Fabian Beyerlein]]></dc:creator>
            <pubDate>Sat, 05 Mar 2022 10:21:23 GMT</pubDate>
            <atom:updated>2022-03-05T10:21:23.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2T-1HiVqnvon85BioxcRg.png" /></figure><p>I first discovered esbuild as a builder for Angular in <a href="https://www.reddit.com/r/Angular2/comments/s60cro/50x_faster_builds_with_esbuild_production_build/">this Reddit post</a>. I was amazed! Seeing this, I thought: “There must be other ways to utilize this!”</p><h3>What is esbuild?</h3><p><a href="https://esbuild.github.io/">esbuild</a> calls itself “An extremely fast JavaScript bundler”. I can definitely confirm that! And the main reason for that is, that it’s written in Go — unlike our ol’ reliable tsc. Also, it’s plugin API makes it extremely flexible. Did I mention that it also has native TypeScript support?</p><h3>What advantages does this bring?</h3><ul><li><strong>Reduced bundle size</strong>: esbuild has two features that enable this — bundling and code-splitting. These features allow us to compile all external dependencies (from our <em>node_modules</em> folder) into the final bundle. Because esbuild can also minify the bundle, this decreases bundle size drastically</li><li><strong>Reduced build time</strong>: Like I mentioned before — esbuild is extremely fast. Combined with a watch mode this makes for crazy fast development speed. Build time for my Function App with 28 Functions: 800ms 🤯 Now, this is only half the truth. esbuild doesn’t do type checking so we have to run tsc --noEmit at least in our CI pipeline (which isn’t quite as fast unfortunately).</li></ul><h3>How do I build Azure Functions with it?</h3><p>Great question! Here’s how you can do it:</p><p>First, install esbuild using npm: npm i -D esbuild</p><p>Then, create a build script in the root of the project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de17f88c46cbad5b8b7368a03af3bac6/href">https://medium.com/media/de17f88c46cbad5b8b7368a03af3bac6/href</a></iframe><p>Now, simply adjust the scriptFile property in every function.json to account for the new file extension and you’re good to go.</p><p>Or are you? 🧐 While writing this article, I fell into some traps and rabbitholes. Like for example:</p><ul><li>__dirname and __filename not being available in ESM</li><li>esbuild not being able to convert CJS requires to ESM imports</li><li>The output directory not being correct when there is only one Azure Function</li></ul><h3>What now?</h3><p>These pitfalls and rabbitholes caused me to develop a tool that catches all of those and allows for easy extension of the esbuild config that I think is a good default. You can also either use it from the CLI or via code (which I would recommend).</p><p>Let’s have a look:</p><p>First, install it in your project using npm: npm i -D esbuild-azure-functions.</p><p>Then, create a build script in the root of the project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b01f6a18b1ec83d7ad1467d153908426/href">https://medium.com/media/b01f6a18b1ec83d7ad1467d153908426/href</a></iframe><p>And that’s the basic config. By default, the tool looks for every index.ts file in the project directory. For a more detailed documentation, checkout the GitHub repo below!</p><h3>Benchmark</h3><p>To wrap it up, here are some of the number I’ve observed</p><h4>Bundle size</h4><p>Bundle size decreased massively. Most of that probably comes from the fact that we don’t just throw the node_modules folder into the app package.</p><p>Now, I’ve included zip file sizes for both Linux and Windows. I run my Node.js Azure Functions on Windows and Windows produces a zip file that’s quite a lot smaller than one created on Linux.</p><figure><img alt="Bundle size comparison" src="https://cdn-images-1.medium.com/max/1024/1*34dVQGL3PQZcaToHlNcsfg.png" /><figcaption>Bundle size comparison</figcaption></figure><h4>Build time</h4><p>As mentioned above, build time is very fast.</p><figure><img alt="Build speed comparison" src="https://cdn-images-1.medium.com/max/1024/1*7ZM8_xCXXpEh4w-mDyXQZQ.png" /><figcaption>Build speed comparison</figcaption></figure><p><a href="https://github.com/beyerleinf/esbuild-azure-functions">GitHub - beyerleinf/esbuild-azure-functions: A builder for Azure Functions powered by esbuild.</a></p><p>I hope you liked this blog post! If you have any questions, feel free to hit me up!</p><p>Cheers!</p><p><em>This story was originally published on my personal blog at </em><a href="https://blog.beyerleinf.de/azure-functions-esbuild"><em>https://blog.beyerleinf.de</em></a></p><p><a href="https://www.buymeacoffee.com/beyerleinf"><em>Wanna buy me a coffee?</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3773ea5b8a62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Application Insights — How not to burn money using it]]></title>
            <link>https://medium.com/@beyerleinf/azure-application-insights-how-not-to-burn-money-using-it-5f1bbe5816b4?source=rss-a186fda9ed3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1bbe5816b4</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[application-insights]]></category>
            <category><![CDATA[money]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Fabian Beyerlein]]></dc:creator>
            <pubDate>Thu, 14 Oct 2021 14:22:29 GMT</pubDate>
            <atom:updated>2021-10-14T23:39:12.712Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Application Insights — How not to burn money using it</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVu7g4dHlgtGYO78RWMi9g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jpvalery?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jp Valery</a> on <a href="https://unsplash.com/s/photos/money?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As Developers, we tend to take things for granted. Especially when it comes to Cloud Services. They make everything seem so easy, you’d be forgiven for taking things for granted. In this blog post, I’m going to talk about Azure Application Insights and how I learned not to take certain things for granted — the hard way.</p><p><strong>Disclaimer:</strong><em> I’m only going to be talking about monitoring Azure Functions, specifically using Node.js. I can’t say much about monitoring VMs or other services.</em></p><h3>What is Azure Application Insights?</h3><p>In Microsofts own words:</p><blockquote>Application Insights, a feature of <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/overview">Azure Monitor</a>, is an extensible Application Performance Management (APM) service for developers and DevOps professionals.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QeNMvNDTcGpyZqsytksCQ.png" /><figcaption>Azure Application Insights Overview</figcaption></figure><p>It basically allows you to monitor your applications during and after development for performance, exceptions and a lot of other things. It also stores the data, allows you to run queries over the data and get alerts.</p><p>If you’re interested, definitely check out the <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview">Microsoft Docs</a> to learn more!</p><h3>How do costs arise from Application Insights?</h3><p>Like with most Cloud Services, the costs for Application Insights come from the data that’s ingested and stored. In the Azure Portal, Microsoft says that for every ingested Gigabyte of data they charge 1.94€ (or ~2.24$). That’s not cheap! If your app generates a Gigabyte of data per day (which isn’t unrealistic if you get a lot of traffic), that would set you back 60€ (or ~69.33$). Per month 😱 60€ per month and we haven’t even brought value to our users yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*jf4HIUS2F4IwXwFXiqs1mQ.png" /></figure><p>For September 2021, Application Insights (aka Log Analytics) made up over 80% of the total cost of my app. Running my app like this is not profitable at all.</p><p>Let’s see how this came to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CW5QEgkuml2ohJlCRlKHg.png" /><figcaption>Application Insight costs overview</figcaption></figure><p>In the image above, you can see the cost overview for Application Insights of an app I developed. The chart on the right shows how much data was ingested on any given day. It also shows how much data of each type was ingested. remoteDependency and metric are the largest. remoteDependency metrics get collected when you access other Azure services, in this case it’s a Storage Account. Unfortunately, I’m still unsure what falls under metric .</p><p>You can also see the sudden explosion of ingested data (from 100 MB per day to over 500 MB). On those days, the requests per day jumped from 13.000 to over 80.000 🤯 That increase didn’t come from a bug in our code but because actual usage of the app increased.</p><p>I felt kind of helpless. The Azure Portal doesn’t provide any obvious way to change what gets ingested into Application Insights. So, let’s look at our options.</p><h3>How to reduce Application Insights costs</h3><p>There are a couple of ways to reduce the costs, some work well others not so well. We’re going to look at them regardless.</p><h4>Option #1: Using host.json (okay-ish)</h4><p>This option is also known as “Codeless monitoring”or “Agent-based monitoring”. Basically, you let the Function Runtime (the Agent) do its magic. This option has the least flexibility in my opinion.</p><p>Every Azure Function App has a host.json file. The host.json file contains settings that affect all Functions in an Azure Function App (see <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json">Microsoft Docs</a>). It has some options regarding Application Insights.</p><p>The most notable ones being:</p><ul><li>logging.applicationInsights.samplingSettings</li><li>logging.logLevel</li></ul><p>So I ended up with a host.json that looked something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68341c65ce667500fce599a23af6338e/href">https://medium.com/media/68341c65ce667500fce599a23af6338e/href</a></iframe><p><strong>What did I do?</strong></p><ul><li>I disabled Live Metrics (which are actually free but I don’t use them), Dependency Tracking and Performance Counters</li><li>I set Log Levels</li><li>I <strong>didn’t</strong> mess with any of the sampling settings (I didn’t have a lot of time playing with the settings and also <a href="https://www.gustavwengel.dk/application-insights-costs-lots-of-money">because of this article</a>).</li></ul><p><strong>What drawbacks does this have?<br></strong><em>TL;DR: The reduction of costs wasn’t that great.</em></p><p>The largest chunk of data was still metric. At least the performance and remoteDependency metrics got disabled. Also, setting the Log Level for Function to &quot;Error&quot; causes only failed requests to show up within Application Insights, so you won’t actually know how many requests are made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*iGIlckVWc3PioHcFmZKKOw.png" /><figcaption>Application Insights costs after editing host.json</figcaption></figure><h4>Option #2: Application Insights SDK (great)</h4><p>This option is also known as “Code-based monitoring”. You use the Application Insights SDK manually in your Azure Functions (or any other code for that matter). This gives us maximum flexibility but comes with a few code changes.</p><p><strong>Step 1: Disable Agent-based monitoring</strong><br>If you’ve enabled Agent-based monitoring, you have to disable it manually (either in the Azure Portal or in your Infrastructure-as-Code). To do that, you have to rename (or remove if you don’t want to use it at all) the APPINSIGHTS_INSTRUMENTATIONKEY App Settings in the <em>Configuration</em> section of your Function App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*vhIj7haEpXlMHdrwJ_3dPw.png" /><figcaption>Function App Configuration</figcaption></figure><p>I renamed mine to APP_INSIGHTS_KEY . Don’t forget to save the settings. After that, Application Insights will be disabled for the Function App which you can see in the <em>Application Insights</em> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqbTvAERrchnQi-wsrVxtA.png" /><figcaption>Function App Application Insights settings</figcaption></figure><p><strong><em>Note</em></strong><em>: Toggling the Enabled button in the Application Insights section will not work. You have to rename or remove the App setting for Application Insights to be disabled.</em></p><p><strong>Step 2: Install Application Insights SDK</strong><br>I’m using Node.js for our Azure Functions, so installing the SDK is as simple as executing npm install -S applicationinsights . The installation might differ if you’re not using Node.js. Follow the <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics">Microsoft Docs</a> to get started for the Language you’re using.</p><p><strong>Step 3: Setup Application Insights SDK</strong><br>There are a couple ways to set this up. The way I did it is the simplest, if you have a lot of Functions and requires the least amount of code change.</p><p>This is the initial folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*DSHBhj9-v2A7Q61yuYeerQ.png" /><figcaption>Initial folder structure</figcaption></figure><p>Pretty standard. index.ts contains the Function code and index.spec.ts contains the unit tests. Now, if you look at the “Azure Function Example” <a href="https://github.com/microsoft/ApplicationInsights-node.js#azure-functions-example">in the GitHub repo for the Application Insights Node.js SDK</a>, you’ll notice that those changes would a) be a nightmare to do for multiple Functions and b) would mean that we can no longer <strong>easily</strong> test our Function code. Also, maintaining the config for the Application Insights SDK in multiple places would definitely not be <strong>DRY</strong> 😉</p><p>So I ended up writing a wrapper that I could just pass my Function into.</p><p>I renamed the index.ts to func.ts and added a new index.ts. Don’t forget to update the imports.</p><p>I can also tell you from experience, that you don’t want to try naming them function.ts so you don’t spend an hour debugging your tests. You can probably figure out why.</p><p>So the folder structure now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*sSOtAN0ZiPBZJkcunt15nw.png" /><figcaption>The updated folder structure</figcaption></figure><p>I wrote two wrappers. One for HTTP triggered Functions and one for the rest of the triggers. I added comments so you can just check out the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83fb6efe8ca2f046fc389058bebc3c28/href">https://medium.com/media/83fb6efe8ca2f046fc389058bebc3c28/href</a></iframe><p>With the wrapper in place, we just need to populate each index.tsfile with the same code and we’re done. Keep in mind that you have full control over how the wrapper looks and what you enable or disable in the Application Insights SDK.</p><p>This is what the index.ts now looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3715347da589c32ec960376d2a81746b/href">https://medium.com/media/3715347da589c32ec960376d2a81746b/href</a></iframe><p>That’s it. If you deploy your Function App, you can see the changes in action.</p><p>The amount of ingested data in my app is now so little, that I’ll have to show another chart to actually see how much it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*JkZF0G2gnvKB4inohItOQw.png" /><figcaption>Application Insights ingested amount after optimization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jESFQP2-yJ2slV8Mp4dtg.png" /><figcaption>Data Point volume after optimization — only about 600KB per day 🥳</figcaption></figure><p>One might get the impression that there’s a lot of metrics missing (or that it’s not working). But so far, I haven’t noticed any missing metrics.</p><h3>Final Thoughts</h3><p>Using the Application Insights SDK sounded scary at first, but I think my wrapper turned out quite well. Now, all of this obviously depends on your needs (and budget). In my case, the application is very much driven by cost. The cost for Application Insights as it is just doesn’t fit in my budget. Maybe you might be able to get away with what can be configured in the host.json file.</p><p>I hope you enjoyed this post. If you have suggestions or questions, hit me up! Cheers!</p><p><em>If you want, you can follow me on twitter: </em><a href="https://twitter.com/byrln"><em>https://twitter.com/byrln</em></a></p><h3>Resources</h3><p><a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview">https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview</a><br><a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/azure-web-apps">https://docs.microsoft.com/en-us/azure/azure-monitor/app/azure-web-apps</a><br><a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json">https://docs.microsoft.com/en-us/azure/azure-functions/functions-host-json</a><br><a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics">https://docs.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics</a><br><a href="https://www.gustavwengel.dk/application-insights-costs-lots-of-money">https://www.gustavwengel.dk/application-insights-costs-lots-of-money</a><br><a href="https://github.com/microsoft/ApplicationInsights-node.js">https://github.com/microsoft/ApplicationInsights-node.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1bbe5816b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Follow-Up: How To Handle Async Providers in Angular]]></title>
            <link>https://medium.com/better-programming/follow-up-how-to-handle-async-providers-in-angular-54957c7349c4?source=rss-a186fda9ed3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/54957c7349c4</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Fabian Beyerlein]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 21:50:35 GMT</pubDate>
            <atom:updated>2019-11-09T15:47:03.478Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this follow-up, I look at a more elegant solution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoJQLToesg1zWPGjeIfSdA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kehfam?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Olu Famule</a> on <a href="https://unsplash.com/s/photos/web-development?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A few weeks ago, I published a <a href="https://medium.com/better-programming/how-to-handle-async-providers-in-angular-51884647366">piece about async providers in Angular</a>.</p><p>In this article, we are going to look at another solution proposed to me by <a href="https://medium.com/u/37d5aaa66657">Александр Кошеверов</a>.</p><h3>What Did We Do Last Time?</h3><p>In my previous solution, we used APP_INITIALIZER to load the config while Angular bootstraps our app. Additionally, we provided the value using an InjectionToken. This solution has a few problems that I discovered while adding it to a project at work — one of them being initialization order. When, for example, another module was also using APP_INITIALIZER, it was often being called before ours, causing the value to be undefined. So get ready for a better version.</p><h3>platformBrowserDynamic Can Do a Bit More!</h3><p>What I missed while implementing the previous solution — guess I should have read the documentation thoroughly — is that the function platformBrowserDynamic() takes an array of providers as a parameter (<a href="https://angular.io/api/platform-browser-dynamic/platformBrowserDynamic">check the documentation</a>). Perfect!</p><p>Now we can do the following:</p><ol><li>Load our config in main.ts using the native fetch-API.</li><li>Provide the value before our application is bootstrapped, thus ensuring the config is always available (given that the source is also available).</li></ol><p>Because this solution is way simpler, we only need to edit the main.ts file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e642dd82db9d1c300c0505690282690/href">https://medium.com/media/0e642dd82db9d1c300c0505690282690/href</a></iframe><ol><li>We wrap everything in an async function to leverage async/await.</li><li>We load our arbitrary config using JavaScripts native fetch-API (L12+L13).</li><li>Pass an array of providers to platformBrowserDynamic() (L17).</li></ol><p>That’s it. You can check the full and updated example<a href="https://github.com/beyerleinf/angular-async-module-providers"> repo on GitHub</a>.</p><h3>Conclusion</h3><p>Always read the docs.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54957c7349c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/follow-up-how-to-handle-async-providers-in-angular-54957c7349c4">Follow-Up: How To Handle Async Providers in Angular</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Handle Async Providers in Angular]]></title>
            <link>https://medium.com/better-programming/how-to-handle-async-providers-in-angular-51884647366?source=rss-a186fda9ed3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/51884647366</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Fabian Beyerlein]]></dc:creator>
            <pubDate>Sat, 21 Sep 2019 20:04:25 GMT</pubDate>
            <atom:updated>2024-07-25T16:17:42.457Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explaining an issue loading the value for a base API URL from a configuration file and using it with an InjectionToken</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avlg0U4o26ozRD2Ft6DT9Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Luca Bravo</a> on <a href="https://unsplash.com/s/photos/angular-web?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Update: I wrote a follow-up story to this with a better solutions here: <a href="https://medium.com/better-programming/follow-up-how-to-handle-async-providers-in-angular-54957c7349c4">https://medium.com/better-programming/follow-up-how-to-handle-async-providers-in-angular-54957c7349c4</a></p><p>If you’re not sure what that title means, don’t worry. Let me explain.<br>I recently ran into an issue where we needed to load the value for a base API URL (e.g., http://localhost:9000) from a configuration file and use that value with an InjectionToken in our app.</p><p>I’m going to explain what I ended up doing in this blog post.</p><h3>APP_INITIALIZER Saves the Day</h3><p>You’re probably familiar with APP_INITIALIZER. If not, I recommend reading <a href="https://indepth.dev/hooking-into-the-angular-bootstrap-process/">this article over on Angular InDepth</a>.</p><p>APP_INITIALIZER lets you hook into Angular’s bootstrapping process to do things before the rest of the app has loaded.</p><h4>The service</h4><p>Let’s create the service for loading the config.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a59ccc79f119559bc559d7daed14b207/href">https://medium.com/media/a59ccc79f119559bc559d7daed14b207/href</a></iframe><p>Pretty simple, right? getBaseUrl() performs a GET<strong> </strong>request on /assets/config.json and uses some <a href="https://rxjs-dev.firebaseapp.com/">RxJS</a><em> </em>magic<em> </em>to extract the property baseUrl from the resulting JSON.</p><p>It also stores the resulting value in a private property baseApiUrl which is exposed with the getter baseUrl. I added loadConfig() in case multiple values need to be loaded. loadConfig() is also what we are going to use for the APP_INITIALZER.</p><h4>The AppLoadModule</h4><p>The AppLoadModule will provide APP_INITIALIZER. The code is also pretty straightforward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eaf6cb7e38cb1a9e926846463a6e4a0/href">https://medium.com/media/8eaf6cb7e38cb1a9e926846463a6e4a0/href</a></iframe><p>We add a factory function which takes our service as the first parameter. In it, we return a function returning a promise — the promise being the thing we want to do.</p><p>Thanks to RxJS, we can use the RxJS goodness throughout our app and convert it to a promise when needed. We could also use the HttpClient directly in the factory function, but the more code you can share within your app, the better.</p><p>The next thing we need to do is provide APP_INITIALIZER.</p><ul><li>useFactory tells Angular which factory function to use. You could also write that in-line.</li><li>deps tells Angular which Services or other injectables are needed to handle the factory. The order in which you put in the deps affects how you need to order the parameters of your function.</li></ul><p>And that’s it for the AppLoadModule.</p><h4>The ConfigModule</h4><p>The last module we need is the ConfigModule. Creating a separate module for this isn’t necessary but can clean things up in larger applications, in my opinion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3a25e8b44061154363060a390277a5/href">https://medium.com/media/5c3a25e8b44061154363060a390277a5/href</a></iframe><p>All we do here is provide an InjectionToken called BASE_API_URL_TOKEN. I used this throughout my app to tell services “where” the API server is.</p><p>We use a factory because we need access to the ConfigService. useFactory and deps do the same things as above with the difference being that factories for providers do not support promises, which is the entire reason this article is even necessary.</p><p>All that’s left to do now, is to import both Modules in your module of choice and you’re good to go.</p><h3>Summary</h3><p>I can’t help but think that there is or should be a better way to do this. I also think the solution I described here isn’t <em>that</em> bad.</p><p>If you want to check out my full example, I created a <a href="https://github.com/beyerleinf/angular-async-module-providers">GitHub repository</a> which you can clone, run, and inspect for yourself.</p><p>Wrapping up, all we really needed to do was use Angular’s APP_INITIALIZER to load configurations before the rest of our application is available and save them in a Service. Providing them is pretty easy once we have them inside our application.</p><p>If you have any suggestions or even better solutions to this, please leave them down below.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51884647366" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-handle-async-providers-in-angular-51884647366">How To Handle Async Providers in Angular</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>