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

<channel>
	<title>onthecode</title>
	<atom:link href="https://onthecode.co.uk/feed" rel="self" type="application/rss+xml" />
	<link>https://onthecode.co.uk/</link>
	<description>onthecode blog</description>
	<lastBuildDate>Tue, 25 Feb 2025 12:10:00 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.3</generator>

<image>
	<url>https://onthecode.co.uk/wp-content/uploads/2019/02/onthecode-icon-1-100x100.png</url>
	<title>onthecode</title>
	<link>https://onthecode.co.uk/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Automating Changelog Updates in Renovate Bot PRs</title>
		<link>https://onthecode.co.uk/blog/automating-changelog-updates-in-renovate-bot-prs</link>
					<comments>https://onthecode.co.uk/blog/automating-changelog-updates-in-renovate-bot-prs#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sun, 23 Feb 2025 11:54:00 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5848</guid>

					<description><![CDATA[<p>When using Renovate Bot for dependency updates in a releaseable project, you might find that adding the changelog update is not done for you. A developer needs to manually check out the renovate PR, run the changelog command e.g. yarn change, and commit the generated change files. This is tedious and slows down the update process. Renovate postUpgradeTasks Renovate provides a postUpgradeTasks feature that allows running commands after an upgrade. We can leverage this to automate changelog updates. Please note this is only available in self-hosted renovate instances. If you are using the hosted version of renovate, a custom pipeline/action can be created to automatically add the changeset commits. Configuration Add the following to your Renovate configuration file (renovate.json): Explanation Benefits ✅ No more manual changelog updates for dependency upgrades.✅ Faster PR handling and merging.✅ Consistent changelog entries. With postUpgradeTasks, Renovate can handle dependency updates more efficiently by automating changelog generation. Try adding this to your workflow and eliminate the manual effort!</p>
<p>The post <a href="https://onthecode.co.uk/blog/automating-changelog-updates-in-renovate-bot-prs">Automating Changelog Updates in Renovate Bot PRs</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>When using Renovate Bot for dependency updates in a releaseable project, you might find that adding the changelog update is not done for you. </p>



<p>A developer needs to manually check out the renovate PR, run the changelog command e.g. <code>yarn change</code>, and commit the generated change files. </p>



<p>This is tedious and slows down the update process.</p>



<h2 class="wp-block-heading">Renovate postUpgradeTasks</h2>



<p>Renovate provides a <a href="https://docs.renovatebot.com/configuration-options/#postupgradetasks" target="_blank" rel="noreferrer noopener"><code>postUpgradeTasks</code></a> feature that allows running commands after an upgrade. </p>



<p>We can leverage this to automate changelog updates.</p>



<p>Please note this is only available in self-hosted renovate instances. If you are using the hosted version of renovate, a custom pipeline/action can be created to automatically add the changeset commits.</p>



<h3 class="wp-block-heading">Configuration</h3>



<p>Add the following to your Renovate configuration file (<code>renovate.json</code>):</p>


<pre class="wp-block-code"><span><code class="hljs language-json shcb-code-table"><span class='shcb-loc'><span>  <span class="hljs-string">"postUpgradeTasks"</span>: {
</span></span><span class='shcb-loc'><span>    <span class="hljs-attr">"commands"</span>: &#91;
</span></span><mark class='shcb-loc'><span>      <span class="hljs-string">"yarn change --type patch --message \"$(git show -s --format=%s | sed 's/\"/\\\"/g')\""</span>
</span></mark><span class='shcb-loc'><span>    ],
</span></span><span class='shcb-loc'><span>    <span class="hljs-attr">"fileFilters"</span>: &#91;<span class="hljs-string">"**/package.json"</span>]
</span></span><span class='shcb-loc'><span>  },
</span></span></code></span></pre>


<h3 class="wp-block-heading">Explanation</h3>



<ul class="wp-block-list">
<li><strong><code>postUpgradeTasks.commands</code></strong>: Runs <code>yarn change</code> automatically, using the latest commit message as the changelog entry.</li>



<li><strong><code>fileFilters</code></strong>: Ensures the command runs only when <code>package.json</code> changes.</li>



<li><strong>Escaping Quotes</strong>: The <code>sed</code> command prevents issues with double quotes in commit messages.</li>
</ul>



<h2 class="wp-block-heading">Benefits</h2>



<p>✅ No more manual changelog updates for dependency upgrades.<br>✅ Faster PR handling and merging.<br>✅ Consistent changelog entries.</p>



<p>With <code>postUpgradeTasks</code>, Renovate can handle dependency updates more efficiently by automating changelog generation. Try adding this to your workflow and eliminate the manual effort!</p>
<p>The post <a href="https://onthecode.co.uk/blog/automating-changelog-updates-in-renovate-bot-prs">Automating Changelog Updates in Renovate Bot PRs</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/automating-changelog-updates-in-renovate-bot-prs/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>What is a Design System?</title>
		<link>https://onthecode.co.uk/blog/what-is-a-design-system</link>
					<comments>https://onthecode.co.uk/blog/what-is-a-design-system#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sat, 22 Feb 2025 18:35:55 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5834</guid>

					<description><![CDATA[<p>Every growing product faces the same challenge: inconsistent UI, duplicated code and design chaos. One team builds a button one way, another team builds it differently. Before you know it, your app looks like a patchwork of mismatched components. What is a Design System? A&#160;design system&#160;is a collection of reusable components, design principles, and guidelines that help teams build consistent and scalable user interfaces. It serves as a&#160;single source of truth&#160;for both designers and developers. Key Elements of a Design System Design Tokens The smallest reusable design properties, such as colors, typography, spacing, and shadows. Instead of hardcoding&#160;#FF5733&#160;as a color, you define&#160;primary-color&#160;and apply it everywhere. Component Library A set of reusable UI elements like buttons, forms and modals that adhere to design and accessibility standards. And to enforce design standards in code, we need a front-end framework (React, Angular, Vue, etc.). Documentation Usage instructions, design principles, and accessibility rules to ensure consistency. How It Works in Practice Imagine you work at a company with multiple teams working on a single product. Instead of every team creating their own version of a &#8220;Submit&#8221; button with slightly different padding, font sizes, and colors, you define a standard button component in your design system. This button is: Why Do Companies Use Design Systems? The world’s leading companies — Google, Airbnb, IBM, and Microsoft — all use design systems to scale their products. Here’s why: Scalability for Large Teams As products grow, maintaining UI consistency becomes harder. A design system provides a structured foundation that scales. Faster Development Developers don’t have to reinvent the wheel every time they build a new feature. With a component library, they can reuse existing components, reducing development time significantly. Consistent UI A design system ensures that every product maintains a cohesive look and feel. Without one, different teams may implement slightly different versions of the same components. Improved Collaboration Designers define the system. Developers implement it. Everyone works from a shared set of rules rather than treating design and development as separate silos. Accessibility and Usability Standards All users, including those with disabilities, should be able to use the product effectively. A design system integrates accessibility best practices into the components from the start. Design System Examples These are some of the great examples of solid design systems that power thousands of apps: Google created&#160;Material Design&#160;as a design system to unify the user experience across Android, web, and mobile apps. It includes everything from typography guidelines to pre-built UI components. Result?&#160;Hundreds of apps now have a consistent and user-friendly UI. How to Build a Design System Creating a design system isn’t an overnight task. Here’s a simplified roadmap to get started: Step 1: Audit Your Existing UI Step 2: Define Design Tokens Step 3: Create a Component Library Step 4: Document Everything Step 5: Adopt a Versioning Strategy Common Challenges (and How to Overcome Them) Even the best design systems face hurdles. Here’s how to tackle them: “Teams resist adoption.”&#160; 💡 Solution: Educate stakeholders on the&#160;time saved&#160;by using pre-built components. Offer workshops or demos. “Keeping the system updated is hard.”&#160; 💡 Solution: Assign a dedicated&#160;design system team&#160;responsible for maintenance and updates. “One-size-fits-all doesn’t work.”&#160; 💡 Solution: Allow for&#160;controlled flexibility. Some components may need customisation per product. Conclusion If your product is growing without a&#160;design system, you’re setting yourself up for&#160;technical debt and UI inconsistency. A well-structured design system helps teams move&#160;faster, collaborate&#160;better, and ship&#160;high-quality, scalable UI. Whether you’re a designer, developer, or product manager, investing in a design system will make your workflow smoother and more efficient.</p>
<p>The post <a href="https://onthecode.co.uk/blog/what-is-a-design-system">What is a Design System?</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Every growing product faces the same challenge: inconsistent UI, duplicated code and design chaos. One team builds a button one way, another team builds it differently. </p>



<p>Before you know it, your app looks like a patchwork of mismatched components.</p>



<h2 class="wp-block-heading"><strong>What is a Design System?</strong></h2>



<p>A&nbsp;<strong>design system</strong>&nbsp;is a collection of reusable components, design principles, and guidelines that help teams build consistent and scalable user interfaces. </p>



<p>It serves as a&nbsp;single source of truth&nbsp;for both designers and developers.</p>



<h2 class="wp-block-heading"><strong>Key Elements of a Design System</strong></h2>



<h3 class="wp-block-heading"><strong>Design Tokens</strong></h3>



<p>The smallest reusable design properties, such as colors, typography, spacing, and shadows. Instead of hardcoding&nbsp;<code>#FF5733</code>&nbsp;as a color, you define&nbsp;<code>primary-color</code>&nbsp;and apply it everywhere.</p>



<h3 class="wp-block-heading"><strong>Component Library</strong></h3>



<p>A set of reusable UI elements like buttons, forms and modals that adhere to design and accessibility standards.</p>



<p>And to enforce design standards in code, we need a front-end framework (React, Angular, Vue, etc.).</p>



<h3 class="wp-block-heading"><strong>Documentation</strong></h3>



<p>Usage instructions, design principles, and accessibility rules to ensure consistency.</p>



<h2 class="wp-block-heading"><strong>How It Works in Practice</strong></h2>



<p>Imagine you work at a company with multiple teams working on a single product.</p>



<p>Instead of every team creating their own version of a &#8220;Submit&#8221; button with slightly different padding, font sizes, and colors, you define a standard button component in your design system.</p>



<p>This button is: </p>



<ul class="wp-block-list">
<li>Styled according to brand guidelines.</li>



<li>Accessible by default (keyboard navigation, proper contrast, etc.). </li>



<li>Easily updated — fix it once, and every instance updates automatically.</li>
</ul>



<h2 class="wp-block-heading"><strong>Why Do Companies Use Design Systems?</strong></h2>



<p>The world’s leading companies — Google, Airbnb, IBM, and Microsoft — all use design systems to scale their products. </p>



<p>Here’s why:</p>



<h3 class="wp-block-heading"><strong>Scalability for Large Teams</strong></h3>



<p>As products grow, maintaining UI consistency becomes harder.</p>



<p>A design system provides a structured foundation that scales.</p>



<h3 class="wp-block-heading"><strong>Faster Development</strong></h3>



<p>Developers don’t have to reinvent the wheel every time they build a new feature. </p>



<p>With a component library, they can reuse existing components, reducing development time significantly.</p>



<h3 class="wp-block-heading"><strong>Consistent UI</strong></h3>



<p>A design system ensures that every product maintains a cohesive look and feel.</p>



<p>Without one, different teams may implement slightly different versions of the same components.</p>



<h3 class="wp-block-heading"><strong>Improved Collaboration</strong></h3>



<p>Designers define the system. </p>



<p>Developers implement it. </p>



<p>Everyone works from a shared set of rules rather than treating design and development as separate silos.</p>



<h3 class="wp-block-heading"><strong>Accessibility and Usability Standards</strong></h3>



<p>All users, including those with disabilities, should be able to use the product effectively.</p>



<p>A design system integrates accessibility best practices into the components from the start.</p>



<h2 class="wp-block-heading">Design System Examples</h2>



<p>These are some of the great examples of solid design systems that power thousands of apps:</p>



<ul class="wp-block-list">
<li>Google’s <a href="https://m3.material.io" target="_blank" rel="noreferrer noopener">Material Design</a></li>



<li>IBM’s <a href="https://carbondesignsystem.com" target="_blank" rel="noreferrer noopener">Carbon</a></li>



<li>Microsoft’s <a href="https://fluent2.microsoft.design" target="_blank" rel="noreferrer noopener">Fluent</a></li>



<li>Atlassian <a href="https://atlassian.design" target="_blank" rel="noreferrer noopener">Design</a></li>
</ul>



<p>Google created&nbsp;Material Design&nbsp;as a design system to unify the user experience across Android, web, and mobile apps. </p>



<p>It includes everything from typography guidelines to pre-built UI components.</p>



<p>Result?&nbsp;Hundreds of apps now have a consistent and user-friendly UI.</p>



<h2 class="wp-block-heading"><strong>How to Build a Design System</strong></h2>



<p>Creating a design system isn’t an overnight task. Here’s a simplified roadmap to get started:</p>



<h3 class="wp-block-heading"><strong>Step 1: Audit Your Existing UI</strong></h3>



<ul class="wp-block-list">
<li>Identify inconsistencies in design and code.</li>



<li>Take inventory of UI components used across your product.</li>
</ul>



<h3 class="wp-block-heading"><strong>Step 2: Define Design Tokens</strong></h3>



<ul class="wp-block-list">
<li>Establish a set of&nbsp;global styles&nbsp;for colors, typography, spacing, and shadows.</li>



<li>Use a tool like&nbsp;<a href="https://amzn.github.io/style-dictionary/#/" target="_blank" rel="noreferrer noopener">Style Dictionary</a>&nbsp;or&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_cascading_variables/Using_CSS_custom_properties" target="_blank" rel="noreferrer noopener">CSS variables</a>&nbsp;to manage tokens.</li>
</ul>



<h3 class="wp-block-heading"><strong>Step 3: Create a Component Library</strong></h3>



<ul class="wp-block-list">
<li>Build and document reusable UI components using&nbsp;<a href="https://storybook.js.org">Storybook</a>.</li>



<li>Ensure each component meets accessibility standards (ARIA roles, keyboard navigation, etc.).</li>
</ul>



<h3 class="wp-block-heading"><strong>Step 4: Document Everything</strong></h3>



<ul class="wp-block-list">
<li>Write clear usage guidelines for each component.</li>



<li>Explain when and how components should be used.</li>



<li>Provide code snippets and design mocks.</li>
</ul>



<h3 class="wp-block-heading"><strong>Step 5: Adopt a Versioning Strategy</strong></h3>



<ul class="wp-block-list">
<li>Use&nbsp;Semantic Versioning (SemVer)&nbsp;to track updates.</li>



<li>Assign&nbsp;ownership — who maintains the design system?</li>



<li>Schedule&nbsp;regular audits&nbsp;to ensure it stays relevant.</li>
</ul>



<h2 class="wp-block-heading"><strong>Common Challenges (and How to Overcome Them)</strong></h2>



<p>Even the best design systems face hurdles. Here’s how to tackle them:</p>



<p><strong>“Teams resist adoption.”</strong>&nbsp;</p>



<p>💡 Solution: Educate stakeholders on the&nbsp;time saved&nbsp;by using pre-built components. Offer workshops or demos.</p>



<p><strong>“Keeping the system updated is hard.”</strong>&nbsp;</p>



<p>💡 Solution: Assign a dedicated&nbsp;design system team&nbsp;responsible for maintenance and updates.</p>



<p><strong>“One-size-fits-all doesn’t work.”</strong>&nbsp;</p>



<p>💡 Solution: Allow for&nbsp;controlled flexibility. Some components may need customisation per product.</p>



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p>If your product is growing without a&nbsp;design system, you’re setting yourself up for&nbsp;technical debt and UI inconsistency.</p>



<p>A well-structured design system helps teams move&nbsp;faster, collaborate&nbsp;better, and ship&nbsp;high-quality, scalable UI. </p>



<p>Whether you’re a designer, developer, or product manager, investing in a design system will make your workflow smoother and more efficient.</p>
<p>The post <a href="https://onthecode.co.uk/blog/what-is-a-design-system">What is a Design System?</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/what-is-a-design-system/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Does Angular require defaultProject property?</title>
		<link>https://onthecode.co.uk/blog/does-angular-require-defaultproject-property</link>
					<comments>https://onthecode.co.uk/blog/does-angular-require-defaultproject-property#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Fri, 25 Aug 2023 10:21:42 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5777</guid>

					<description><![CDATA[<p>Migrating your Angular project to version 14 will automatically remove the defaultProject property in angular.json for single project workspaces. Let&#8217;s understand what defaultProject is and when you might need it. What is default project in Angular? In Angular, a &#8220;default project&#8221; refers to the primary application or module within an Angular workspace. An Angular workspace is essentially a project container that can hold multiple projects, each of which can be an Angular application, library, or other related modules. When you create a new Angular workspace using the Angular CLI, it automatically generates a default project for you. This default project is often named &#8220;app&#8221; by default. It serves as the main entry point for your application and includes the initial components, modules, services, and other files necessary to get your Angular application up and running. You can also specify a different name for the default project during the creation of the workspace using the --defaultProject flag: In this case, the default project is going to be &#8220;my-default-app&#8221; instead of the usual &#8220;app.&#8221; Why do we need to specify defaultProject in Angular? You can have multiple projects within a single Angular workspace e.g., an admin panel and a user-facing frontend. Each project can have its own configuration, dependencies, and codebase.But they can also share common resources and libraries within the workspace. Angular CLI assumes you may create multiple projects in your workspace. And tries to help you by specifying the default project for you. Does angular require defaultProject in angular json file? Angular itself does not require a defaultProject in the angular.json file. The defaultProject property is completely optional. It specifies which project to build &#38; serve when a project name is not provided in the command line. However, there is an exception. If you have multiple projects in your workspace and you&#8217;re running a command that requires a project name (like ng serve or ng build) without specifying a project, then defaultProject is needed to tell Angular which project to apply the command to. If you only have one project in your workspace, or you always specify your project when running commands, then you don&#8217;t need&#160;defaultProject. In conclusion, Angular 14 (or any version) does not require defaultProject, but it can be helpful in multi-project workspaces.</p>
<p>The post <a href="https://onthecode.co.uk/blog/does-angular-require-defaultproject-property">Does Angular require defaultProject property?</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Migrating your <a href="http://angular.io">Angular</a> project to version 14 will automatically remove the <strong>defaultProject</strong> property in <code>angular.json</code> for single project workspaces. </p>



<p>Let&#8217;s understand what defaultProject is and when you might need it. </p>



<h2 class="wp-block-heading">What is default project in Angular?</h2>



<p>In <a href="/blog/category/angular">Angular</a>, a &#8220;default project&#8221; refers to the primary application or module within an Angular workspace. </p>



<p>An Angular workspace is essentially a project container that can hold multiple projects, each of which can be an Angular application, library, or other related modules.</p>



<p>When you create a new Angular workspace using the Angular CLI, it automatically generates a default project for you. </p>


<pre class="wp-block-code"><span><code class="hljs language-bash">ng new my-angular-app</code></span></pre>


<p>This default project is often named &#8220;app&#8221; by default. </p>



<p>It serves as the main entry point for your application and includes the initial components, modules, services, and other files necessary to get your Angular application up and running.</p>



<p>You can also specify a different name for the default project during the creation of the workspace using the <code>--defaultProject</code> flag:</p>


<pre class="wp-block-code"><span><code class="hljs language-bash">ng new my-angular-app --defaultProject=my-default-app</code></span></pre>


<p>In this case, the default project is going to be &#8220;my-default-app&#8221; instead of the usual &#8220;app.&#8221;</p>



<h2 class="wp-block-heading">Why do we need to specify defaultProject in Angular?</h2>



<p>You can have multiple projects within a single Angular workspace e.g., an admin panel and a user-facing frontend.</p>



<p>Each project can have its own configuration, dependencies, and codebase.But they can also share common resources and libraries within the workspace.</p>



<p>Angular CLI assumes you may create multiple projects in your workspace. And tries to help you by specifying the default project for you.</p>



<h2 class="wp-block-heading">Does angular require defaultProject in angular json file?</h2>



<p>Angular itself does not require a <code>defaultProject</code> in the <code>angular.json</code> file.</p>



<p>The <code>defaultProject</code> property is completely optional. It specifies which project to build &amp; serve when a project name is not provided in the command line.</p>



<p>However, there is an exception. </p>



<p>If you have multiple projects in your workspace and you&#8217;re running a command that requires a project name (like <code>ng serve</code> or <code>ng build</code>) without specifying a project, then <code>defaultProject</code> is needed to tell Angular which project to apply the command to.</p>



<p>If you only have one project in your workspace, or you always specify your project when running commands, then you don&#8217;t need&nbsp;<code>defaultProject</code>.</p>



<p>In conclusion, Angular 14 (or any version) does not require <code>defaultProject</code>, but it can be helpful in multi-project workspaces.</p>



<p></p>



<p></p>
<p>The post <a href="https://onthecode.co.uk/blog/does-angular-require-defaultproject-property">Does Angular require defaultProject property?</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/does-angular-require-defaultproject-property/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create a Bean of Class from a Java Library in Spring Boot</title>
		<link>https://onthecode.co.uk/blog/how-to-create-a-bean-of-class-from-a-java-library-in-spring-boot</link>
					<comments>https://onthecode.co.uk/blog/how-to-create-a-bean-of-class-from-a-java-library-in-spring-boot#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Wed, 23 Aug 2023 14:26:26 +0000</pubDate>
				<category><![CDATA[Spring Boot]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5755</guid>

					<description><![CDATA[<p>Spring Boot is a powerful framework that simplifies the development of Java-based applications. One of its key features is the ability to easily incorporate external libraries into your project. By creating a bean of class from a Java library, you can easily inject it into a constructor instead of creating concrete dependencies. In this article, I&#8217;ll show you the process of creating a bean of class from a Java library. What is a Java library and why use it in Spring Boot? Before we dive in, let&#8217;s understand what a Java library is and why it&#8217;s beneficial to use one in your application. A Java library is a collection of pre-compiled classes, methods, and other resources that provide additional functionality and features to your application. These libraries are created by developers to solve common problems and offer reusable code that can be easily integrated into projects. Using a Java library in your Spring Boot application can save you a significant amount of time and effort. Instead of reinventing the wheel and writing code from scratch, you can leverage the functionality provided by the library, allowing you to focus on the core logic of your application. This approach promotes code reusability and modularity, enabling you to build robust and scalable applications. Creating a bean of a class from a Java library Let&#8217;s explore the steps required to create a bean for a class from the library. The first step is to add the Java library as a dependency in your project. This can be done by updating the build.gradle file for Gradle projects. Once the dependency is added, you&#8217;ll need to refresh your project to ensure the library is downloaded and available for use. Next, you&#8217;ll need to configure the bean in the application context. The application context is where you define the entry point with @SpringBootApplication. It is responsible for managing the beans in your application. @Bean annotation allows you to define the bean directly in your Java code. We will simply annotate a method with @Bean and specify the class of the bean. Spring Boot will automatically create and manage the bean for you. Start with annotating the entry point of your Spring Boot application with @Configuration as shown above. Next, simply create a method and annotate it with @Bean. Specify the return type of the method as the class of the bean. Injecting the bean into other components Now that we have successfully configured the bean in the application context, let&#8217;s explore how to inject the bean into other components of your Spring Boot application. Dependency injection is a key feature of Spring Boot that allows you to easily manage and wire together the components of your application. By injecting the bean into other components, you can utilise its functionality and leverage its capabilities. There are several ways to inject the bean into other components. The most common approach is to use constructor injection. This involves adding a constructor to the component class and specifying the bean as a parameter. Spring Boot will automatically inject the bean when creating an instance of the component. Another approach is to use field injection. This involves adding a field to the component class and annotating it with @Autowired. Spring Boot will automatically inject the bean into the field when creating an instance of the component. You can also use setter injection, where you add a setter method to the component class and annotate it with @Autowired. Spring Boot will invoke the setter method and inject the bean before initialising the component. Using the bean in Spring Boot applications Now that we&#8217;ve covered the process of creating and configuring a bean from a Java library in Spring Boot, let&#8217;s explore how to use the bean in your applications. Once you configure and inject the bean into your components, you can access its methods and properties just like any other object in your application. This allows you to leverage the functionality provided by the Java library within your Spring Boot application. To use the bean, simply call its methods or access its properties in your code. You can also pass the bean as a parameter to other methods or components, allowing you to utilise its functionality throughout your application. It&#8217;s important to note that the bean&#8217;s lifecycle is managed by Spring Boot, so you don&#8217;t need to worry about creating or destroying the bean yourself. Spring Boot will handle the instantiation, initialisation, and destruction of the bean automatically. Common challenges and troubleshooting when creating a bean from a Java library While creating a bean from a Java library in Spring Boot is generally straightforward, there may be some challenges or issues that you encounter along the way. Let&#8217;s explore some common challenges and troubleshooting techniques to help you overcome these obstacles. One common challenge is ensuring that the Java library is properly added as a dependency in your project. Double-check the pom.xml or build.gradle file to ensure that the library is correctly specified. Make sure to refresh your project to download the library if necessary. Another challenge may arise when configuring the bean in the application context. Ensure you specify the class of the bean and that configure any dependencies properly. Double-check the XML-based or annotation-based configuration to ensure accuracy. If you&#8217;re experiencing issues with dependency injection, verify that the bean is properly injected into your components. Check for any missing @Autowired annotations or incorrect usage of constructor, field, or setter injection. Ensure that the bean is accessible within the component&#8217;s scope. If you&#8217;re still encountering issues, refer to the documentation of the Java library and Spring Boot for any specific troubleshooting steps. Additionally, consider reaching out to the developer community or support channels for assistance. Conclusion In this article, we explored the process of creating a bean of class from a Java library in Spring Boot. We discussed the benefits of using Java libraries in your Spring Boot application, the steps to create a bean, and the process of configuring the</p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-create-a-bean-of-class-from-a-java-library-in-spring-boot">How to Create a Bean of Class from a Java Library in Spring Boot</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><a href="https://spring.io/projects/spring-boot" target="_blank" rel="noreferrer noopener">Spring Boot</a> is a powerful framework that simplifies the development of Java-based applications. One of its key features is the ability to easily incorporate external libraries into your project. By creating a bean of class from a Java library, you can easily inject it into a constructor instead of creating concrete dependencies.</p>



<p>In this article, I&#8217;ll show you the process of creating a bean of class from a Java library.</p>



<h2 class="wp-block-heading">What is a Java library and why use it in Spring Boot?</h2>



<p>Before we dive in, let&#8217;s understand what a Java library is and why it&#8217;s beneficial to use one in your application.</p>



<p>A Java library is a collection of pre-compiled classes, methods, and other resources that provide additional functionality and features to your application. These libraries are created by developers to solve common problems and offer reusable code that can be easily integrated into projects.</p>



<p>Using a Java library in your <a href="/blog/category/spring-boot">Spring Boot</a> application can save you a significant amount of time and effort. Instead of reinventing the wheel and writing code from scratch, you can leverage the functionality provided by the library, allowing you to focus on the core logic of your application.</p>



<p>This approach promotes code reusability and modularity, enabling you to build robust and scalable applications.</p>



<h2 class="wp-block-heading">Creating a bean of a class from a Java library</h2>



<p>Let&#8217;s explore the steps required to create a bean for a class from the library.</p>



<p>The first step is to add the Java library as a dependency in your project. This can be done by updating the <code>build.gradle</code> file for Gradle projects. Once the dependency is added, you&#8217;ll need to refresh your project to ensure the library is downloaded and available for use.</p>



<p>Next, you&#8217;ll need to configure the bean in the application context. The application context is where you define the entry point with <code>@SpringBootApplication</code>. It is responsible for managing the beans in your application. </p>



<p><code>@Bean</code> annotation allows you to define the bean directly in your Java code. We will simply annotate a method with <code>@Bean</code> and specify the class of the bean. </p>



<p>Spring Boot will automatically create and manage the bean for you.</p>


<pre class="wp-block-code"><span><code class="hljs language-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@SpringBootApplication</span>()
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyServiceApp</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String&#91;] args)</span> </span>{
        SpringApplication.run(MyServiceApp <span class="hljs-class">.<span class="hljs-keyword">class</span>, <span class="hljs-title">args</span>)</span>;
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> PdfConverter <span class="hljs-title">pdfConverter</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> PdfConverter();
    }
}</code></span></pre>


<p>Start with annotating the entry point of your Spring Boot application with <code>@Configuration</code> as shown above. </p>



<p>Next, simply create a method and annotate it with <code>@Bean</code>. Specify the return type of the method as the class of the bean.</p>



<h2 class="wp-block-heading">Injecting the bean into other components</h2>



<p>Now that we have successfully configured the bean in the application context, let&#8217;s explore how to inject the bean into other components of your Spring Boot application.</p>



<p>Dependency injection is a key feature of Spring Boot that allows you to easily manage and wire together the components of your application. By injecting the bean into other components, you can utilise its functionality and leverage its capabilities.</p>



<p>There are several ways to inject the bean into other components. The most common approach is to use constructor injection. This involves adding a constructor to the component class and specifying the bean as a parameter. Spring Boot will automatically inject the bean when creating an instance of the component.</p>


<pre class="wp-block-code"><span><code class="hljs language-java">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DocumentFormatter</span><span class="hljs-params">(PdfConverter pdfConverter)</span> </span>{
        <span class="hljs-keyword">this</span>.pdfConverter = pdfConverter;
    }</code></span></pre>


<p>Another approach is to use field injection. This involves adding a field to the component class and annotating it with <code>@Autowired</code>. Spring Boot will automatically inject the bean into the field when creating an instance of the component.</p>


<pre class="wp-block-code"><span><code class="hljs language-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> PdfConverter pdfConverter;
}</code></span></pre>


<p>You can also use setter injection, where you add a setter method to the component class and annotate it with <code>@Autowired</code>. Spring Boot will invoke the setter method and inject the bean before initialising the component.</p>


<pre class="wp-block-code"><span><code class="hljs language-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{

    <span class="hljs-keyword">private</span> PdfConverter pdfConverter;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">set</span><span class="hljs-params">(PdfConverter pdfConverter)</span> </span>{
        <span class="hljs-keyword">this</span>.pdfConverter = pdfConverter;
    }
}</code></span></pre>


<h2 class="wp-block-heading">Using the bean in Spring Boot applications</h2>



<p>Now that we&#8217;ve covered the process of creating and configuring a bean from a Java library in Spring Boot, let&#8217;s explore how to use the bean in your applications.</p>



<p>Once  you configure and inject the bean into your components, you can access its methods and properties just like any other object in your application. This allows you to leverage the functionality provided by the Java library within your Spring Boot application.</p>



<p>To use the bean, simply call its methods or access its properties in your code. You can also pass the bean as a parameter to other methods or components, allowing you to utilise its functionality throughout your application.</p>



<p>It&#8217;s important to note that the bean&#8217;s lifecycle is managed by Spring Boot, so you don&#8217;t need to worry about creating or destroying the bean yourself. Spring Boot will handle the instantiation, initialisation, and destruction of the bean automatically.</p>



<h2 class="wp-block-heading">Common challenges and troubleshooting when creating a bean from a Java library</h2>



<p>While creating a bean from a Java library in Spring Boot is generally straightforward, there may be some challenges or issues that you encounter along the way. Let&#8217;s explore some common challenges and troubleshooting techniques to help you overcome these obstacles.</p>



<p>One common challenge is ensuring that the Java library is properly added as a dependency in your project. Double-check the <code>pom.xml</code> or <code>build.gradle</code> file to ensure that the library is correctly specified. Make sure to refresh your project to download the library if necessary.</p>



<p>Another challenge may arise when configuring the bean in the application context. Ensure you specify the class of the bean and that configure any dependencies properly. Double-check the XML-based or annotation-based configuration to ensure accuracy.</p>



<p>If you&#8217;re experiencing issues with dependency injection, verify that the bean is properly injected into your components. Check for any missing <code>@Autowired</code> annotations or incorrect usage of constructor, field, or setter injection. Ensure that the bean is accessible within the component&#8217;s scope.</p>



<p>If you&#8217;re still encountering issues, refer to the documentation of the Java library and Spring Boot for any specific troubleshooting steps. Additionally, consider reaching out to the developer community or support channels for assistance.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this article, we explored the process of creating a bean of class from a Java library in Spring Boot. We discussed the benefits of using Java libraries in your Spring Boot application, the steps to create a bean, and the process of configuring the bean in the application context. We also covered how to inject the bean into other components and the usage of the bean in Spring Boot applications.</p>



<p>Happy coding!</p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-create-a-bean-of-class-from-a-java-library-in-spring-boot">How to Create a Bean of Class from a Java Library in Spring Boot</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/how-to-create-a-bean-of-class-from-a-java-library-in-spring-boot/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Change Detection in Angular: Default vs OnPush</title>
		<link>https://onthecode.co.uk/blog/change-detection-in-angular-default-vs-onpush</link>
					<comments>https://onthecode.co.uk/blog/change-detection-in-angular-default-vs-onpush#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sun, 12 Feb 2023 22:07:26 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5611</guid>

					<description><![CDATA[<p>One of the most loved features of Angular is its ability to automatically update the view whenever data changes. This is thanks to the default Angular&#8217;s change detection mechanism, which constantly checks for changes in data and updates the view accordingly. While this is great for most use cases, it is possible to manually detect changes for performance optimisation. Let&#8217;s explore change detection strategies in Angular. What is a change detection strategy? A change detection strategy is a mechanism that decides when Angular should update the view of a component. Angular offers the following change detection strategies: Any newly generated component uses the default strategy. ChangeDetectionStrategy.Default Default strategy triggers change detection for DOM events, timers, promises, XHR, observables etc. Therefore, every time something changes in our application, a change detection will run on all components to update the view. Angular achieves this by creating a change detector, which is responsible for listening to changes and updating the view of the component. ChangeDetectionStrategy.OnPush The OnPush strategy can be used to optimise the performance of an Angular application. With OnPush strategy, Angular only performs a change detection cycle on a component and its children, if there is a change in the component&#8217;s input properties or if an event is triggered. OnPush triggers change detection when: If the component&#8217;s data model is updated outside of Angular&#8217;s change detection mechanism, Angular will not update the view. This may sound like a drawback, but it&#8217;s actually a useful feature when used correctly. The OnPush strategy is designed to reduce the number of unnecessary change detection cycles. This is especially important in complex applications, where change detection can become a bottleneck and degrading overall performance of the application. How to use onPush strategy To use the OnPush strategy, you simply need to set the changeDetection property of the component&#8217;s @Component decorator to ChangeDetectionStrategy.OnPush. Here&#8217;s an example: It&#8217;s important to note that when using the OnPush strategy, you need to make sure that Angular is aware of any changes in the component&#8217;s data model. This can be done by using the markForCheck method from the ChangeDetectorRef class. The ChangeDetectorRef class provides a way to interact with the change detection mechanism and manually trigger change detection. You can mark a component or its ancestors for checking using the markForCheck method. Next time change detection runs, the view will reflect the new state of data. markForCheck() vs detectChanges() Another method available on the change detector is detectChanges. You might be wondering, what is the difference between markForCheck and detectChanges. The key difference between these is that&#160;detectChanges()&#160;triggers change detection, while&#160;markForCheck()&#160;doesn&#8217;t trigger change detection. With detectChanges(), the change detection will run for the current component and all its children. This is a common fix to the infamous error Expression has changed after it was checked. On the other hand, markForCheck() simply goes upwards from the current component to the root component and updates their view state to&#160;ChecksEnabled. The change detection for the component will happen in the future either as part of the current or next change detection cycle. The parent component views will also be checked even if they had detached change detectors.&#160; Should I use onPush strategy? If change detection is a bottle-neck in your component, go ahead and try onPush change detection strategy. This is a great way to fine-tune the performance of your application. However, premature optimisation can have an adverse effect on your application. If you use onPush strategy without a valid reason, the component code will be more complex, harder to test and more difficult to maintain. Based on my experience, the default strategy will work just fine for most small to medium sized applications. Conclusion In this post, we&#8217;ve looked at the different change detection strategies available in Angular. Default strategy automatically updates view when there is a change in the data model. OnPush strategy allows us to optimise performance by giving us the freedom to choose when to check for changes.</p>
<p>The post <a href="https://onthecode.co.uk/blog/change-detection-in-angular-default-vs-onpush">Change Detection in Angular: Default vs OnPush</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>One of the most loved features of <a href="/blog/category/angular" target="_blank" rel="noreferrer noopener">Angular</a> is its ability to automatically update the view whenever data changes.</p>



<p>This is thanks to the default Angular&#8217;s change detection mechanism, which constantly checks for changes in data and updates the view accordingly. While this is great for most use cases, it is possible to manually detect changes for performance optimisation.</p>



<p>Let&#8217;s explore change detection strategies in Angular.</p>



<h2 class="wp-block-heading">What is a change detection strategy?</h2>



<p>A change detection strategy is a mechanism that decides when Angular should update the view of a component.</p>



<p>Angular <a href="https://angular.io/api/core/ChangeDetectionStrategy" target="_blank" rel="noreferrer noopener">offers</a> the following change detection strategies:</p>



<ul class="wp-block-list">
<li>ChangeDetectionStrategy.<strong>Default</strong></li>



<li>ChangeDetectionStrategy.<strong>OnPush</strong></li>
</ul>



<p>Any newly generated component uses the default strategy. </p>



<h2 class="wp-block-heading">ChangeDetectionStrategy.Default</h2>



<p>Default strategy triggers change detection for DOM events, timers, promises, XHR, observables etc. Therefore, every time something changes in our application, a change detection will run on all components to update the view.</p>



<p>Angular achieves this by creating a change detector, which is responsible for listening to changes and updating the view of the component.</p>



<h2 class="wp-block-heading">ChangeDetectionStrategy.OnPush</h2>



<p>The <code>OnPush</code> strategy can be used to optimise the performance of an Angular application.</p>



<p>With OnPush strategy, Angular only performs a change detection cycle on a component and its children, if there is a change in the component&#8217;s input properties or if an event is triggered.</p>



<p>OnPush triggers change detection when:</p>



<ul class="wp-block-list">
<li>DOM events listened by the component emit</li>



<li><code>async</code>&nbsp;pipe receives a new event</li>



<li><code>@Input()</code>&nbsp;property updates by change detection</li>



<li>Explicitly registration using&nbsp;<code>ChangeDetectorRef::markForCheck</code></li>
</ul>



<p>If the component&#8217;s data model is updated outside of Angular&#8217;s change detection mechanism, Angular will not update the view.</p>



<p>This may sound like a drawback, but it&#8217;s actually a useful feature when used correctly. </p>



<p>The <code>OnPush</code> strategy is designed to reduce the number of unnecessary change detection cycles. This is especially important in complex applications, where change detection can become a bottleneck and degrading overall performance of the application.</p>



<h2 class="wp-block-heading">How to use onPush strategy</h2>



<p>To use the <code>OnPush</code> strategy, you simply need to set the <code>changeDetection</code> property of the component&#8217;s <code>@Component</code> decorator to <code>ChangeDetectionStrategy.OnPush</code>. </p>



<p>Here&#8217;s an example:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { ChangeDetectionStrategy, Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span><span class="hljs-meta">@Component</span>({
</span></span><span class='shcb-loc'><span>  selector: <span class="hljs-string">'app-hello-world'</span>,
</span></span><span class='shcb-loc'><span>  template: <span class="hljs-string">`</span>
</span></span><span class='shcb-loc'><span><span class="hljs-string">    &lt;p&gt;{{ message }}&lt;/p&gt;</span>
</span></span><span class='shcb-loc'><span><span class="hljs-string">  `</span>,
</span></span><mark class='shcb-loc'><span>  changeDetection: ChangeDetectionStrategy.OnPush
</span></mark><span class='shcb-loc'><span>})
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> HelloWorldComponent {
</span></span><span class='shcb-loc'><span>  message = <span class="hljs-string">'Hello, World!'</span>;
</span></span><span class='shcb-loc'><span>}
</span></span></code></span></pre>


<p>It&#8217;s important to note that when using the <code>OnPush</code> strategy, you need to make sure that Angular is aware of any changes in the component&#8217;s data model.</p>



<p>This can be done by using the  <code>markForCheck</code> method from the <code>ChangeDetectorRef</code> class.</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { ChangeDetectorRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> cd: ChangeDetectorRef</span>) { }
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span>ngOnInit() {
</span></span><span class='shcb-loc'><span>  <span class="hljs-comment">// Do some work that changes data</span>
</span></span><mark class='shcb-loc'><span>  <span class="hljs-keyword">this</span>.cd.markForCheck();
</span></mark><span class='shcb-loc'><span>}
</span></span></code></span></pre>


<p>The <code>ChangeDetectorRef</code> class provides a way to interact with the change detection mechanism and manually trigger change detection. </p>



<p>You can mark a component or its ancestors for checking using the <code>markForCheck </code>method. Next time change detection runs, the view will reflect the new state of data.</p>



<h2 class="wp-block-heading">markForCheck() vs detectChanges()</h2>



<p>Another method available on the change detector is <code>detectChanges</code>. You might be wondering, what is the difference between markForCheck and detectChanges.</p>



<p>The key difference between these is that&nbsp;<code>detectChanges()</code>&nbsp;triggers change detection, while&nbsp;<code>markForCheck()</code>&nbsp;doesn&#8217;t trigger change detection.</p>



<p>With <code>detectChanges</code>(), the change detection will run for the current component and all its children. This is a common fix to the infamous error <strong>Expression has changed after it was checked</strong>.</p>



<p>On the other hand, <code>markForCheck()</code> simply goes upwards from the current component to the root component and updates their view state to&nbsp;<code>ChecksEnabled</code>. The change detection for the component will happen in the future either as part of the current or next change detection cycle. The parent component views will also be checked even if they had detached change detectors.&nbsp;</p>



<h2 class="wp-block-heading">Should I use onPush strategy?</h2>



<p>If change detection is a bottle-neck in your component, go ahead and try <code>onPush</code> change detection strategy. This is a great way to fine-tune the performance of your application.</p>



<p>However, premature optimisation can have an adverse effect on your application.</p>



<p>If you use <code>onPush</code> strategy without a valid reason, the component code will be more complex, harder to test and more difficult to maintain.</p>



<p>Based on my experience, the default strategy will work just fine for most small to medium sized applications.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this post, we&#8217;ve looked at the different change detection strategies available in Angular. Default strategy automatically updates view when there is a change in the data model. OnPush strategy allows us to optimise performance by giving us the freedom to choose when to check for changes.</p>
<p>The post <a href="https://onthecode.co.uk/blog/change-detection-in-angular-default-vs-onpush">Change Detection in Angular: Default vs OnPush</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/change-detection-in-angular-default-vs-onpush/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Set Page Title Based on Route in Angular</title>
		<link>https://onthecode.co.uk/blog/how-to-set-page-title-based-on-route-in-angular</link>
					<comments>https://onthecode.co.uk/blog/how-to-set-page-title-based-on-route-in-angular#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sun, 29 Jan 2023 17:44:05 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=4557</guid>

					<description><![CDATA[<p>In this post, I will show you how to set page title based on route in Angular. Angular provides a built-in Title service that we can use to set the title of the web page dynamically from code. We will use the title service in combination with router events to change page title for all routes. Setting page title in Angular Firstly, import the Title service in the component you want to set the title: Inject the Title service in the constructor of the component: Then you can use the setTitle method of the Title service to set the title of the web page. For example, you can set the title based on the data received from a service or from the component&#8217;s properties: As you can see, it is pretty straightforward to use set the title in Angular. Setting the title for all routes Instead of setting the title in every component that&#8217;s associated with a route, we&#8217;ll take it a step further and dynamically set the title from the routes table. DRY (don&#8217;t repeat yourself) is a principle in software development that recommends to do something once, and only once. The first step is to update routes table in every feature module to hold page titles. You should now go through all routes of your app and make sure there is a title associated with every route! Next, generate a service to get data from the current route: Implement the service with below code: This service allows us to pull out the data object we defined in our routes earlier. Like any other singleton service, we can inject it into any component to set the title. Since we want to set the title for every page, we need to subscribe to router events in the root component app.component.ts. Let&#8217;s to update app.component.ts to read the title every time navigation occurs: By using this method, you can set the title of the web page dynamically based on the data from the router events, which will update the title of the window in real-time. Conclusion In summary, we learned how to set the page title in Angular. Through DRY principle, we implemented a feature that sets the page title based on Angular router events. Let me know what you think by dropping a comment below!</p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-set-page-title-based-on-route-in-angular">How to Set Page Title Based on Route in Angular</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this post, I will show you how to set page title based on route in Angular.</p>



<p><a href="/blog/category/angular">Angular</a> provides a built-in <a href="https://angular.io/api/platform-browser/Title" target="_blank" rel="noreferrer noopener">Title</a> service that we can use to set the title of the web page dynamically from code. We will use the title service in combination with router events to change page title for all routes. </p>



<h2 class="wp-block-heading">Setting page title in Angular</h2>



<p>Firstly, import the Title service in the component you want to set the title:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">import</span> { Title } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;</code></span></pre>


<p>Inject the <code>Title</code> service in the constructor of the component:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> titleService: Title</span>) {}</code></span></pre>


<p>Then you can use the <code>setTitle</code> method of the <code>Title</code> service to set the title of the web page. </p>



<p>For example, you can set the title based on the data received from a service or from the component&#8217;s properties:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">this</span>.title.setTitle(<span class="hljs-string">`My Awesome App - <span class="hljs-subst">${data.title}</span>`</span>);</code></span></pre>


<p>As you can see, it is pretty straightforward to use set the title in Angular.</p>



<h2 class="wp-block-heading">Setting the title for all routes</h2>



<p>Instead of setting the title in every component that&#8217;s associated with a route, we&#8217;ll take it a step further and dynamically set the title from the routes table.</p>



<p class="info-block">DRY (don&#8217;t repeat yourself) is a principle in software development that recommends to do something once, and only once.</p>



<p>The first step is to update routes table in every feature module to hold page titles.</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-keyword">const</span> routes: Routes = &#91;
</span></span><span class='shcb-loc'><span>  {
</span></span><span class='shcb-loc'><span>    path: <span class="hljs-string">""</span>,
</span></span><span class='shcb-loc'><span>    component: HomePageComponent,
</span></span><span class='shcb-loc'><span>    data: {
</span></span><mark class='shcb-loc'><span>      title: <span class="hljs-string">"Home"</span>
</span></mark><span class='shcb-loc'><span>    }
</span></span><span class='shcb-loc'><span>  },
</span></span><span class='shcb-loc'><span>  {
</span></span><span class='shcb-loc'><span>    path: <span class="hljs-string">"blog"</span>,
</span></span><span class='shcb-loc'><span>    component: BlogPageComponent,
</span></span><span class='shcb-loc'><span>    data: {
</span></span><mark class='shcb-loc'><span>      title: <span class="hljs-string">"Blog"</span>
</span></mark><span class='shcb-loc'><span>    }
</span></span><span class='shcb-loc'><span>  },
</span></span><span class='shcb-loc'><span>  {
</span></span><span class='shcb-loc'><span>    path: <span class="hljs-string">"**"</span>,
</span></span><span class='shcb-loc'><span>    component: NotFoundPageComponent,
</span></span><span class='shcb-loc'><span>    data: {
</span></span><mark class='shcb-loc'><span>      title: <span class="hljs-string">"Not Found"</span>
</span></mark><span class='shcb-loc'><span>    }
</span></span><span class='shcb-loc'><span>  }
</span></span><span class='shcb-loc'><span>];
</span></span></code></span></pre>


<p>You should now go through all routes of your app and make sure there is a title associated with every route!</p>



<p>Next, generate a service to get <code>data</code> from the current route:</p>


<pre class="wp-block-code"><span><code class="hljs language-bash">ng generate service route-data</code></span></pre>


<p>Implement the service with below code:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">"@angular/core"</span>;
<span class="hljs-keyword">import</span> { ActivatedRoute, ActivatedRouteSnapshot, Data } <span class="hljs-keyword">from</span> <span class="hljs-string">"@angular/router"</span>;

<span class="hljs-meta">@Injectable</span>({
  providedIn: <span class="hljs-string">"root"</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> RouteDataService {

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> route: ActivatedRoute</span>) { }

  <span class="hljs-keyword">get</span>(): Data {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getRouteSnapshot().data;
  }

  <span class="hljs-keyword">private</span> getRouteSnapshot(): ActivatedRouteSnapshot {
    <span class="hljs-keyword">let</span> route = <span class="hljs-keyword">this</span>.route;

    <span class="hljs-keyword">while</span> (route.firstChild) {
      route = route.firstChild;
    }

    <span class="hljs-keyword">return</span> route.snapshot;
  }
}
</code></span></pre>


<p>This service allows us to pull out the <code>data</code> object we defined in our routes earlier.</p>



<p>Like any other singleton service, we can inject it into any component to set the title.</p>



<p>Since we want to set the title for every page, we need to subscribe to router events in the root component <code>app.component.ts</code>.</p>



<p>Let&#8217;s to update <code>app.component.ts</code> to read the title every time navigation occurs:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { filter } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { Component, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { Title } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { NavigationEnd, Router } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/router'</span>;
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { RouteDataService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./route-data.service'</span>;
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span><span class="hljs-meta">@Component</span>({
</span></span><span class='shcb-loc'><span>  selector: <span class="hljs-string">'app-root'</span>,
</span></span><span class='shcb-loc'><span>  templateUrl: <span class="hljs-string">'./app.component.html'</span>,
</span></span><span class='shcb-loc'><span>  styleUrls: &#91;<span class="hljs-string">'./app.component.scss'</span>]
</span></span><span class='shcb-loc'><span>})
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent <span class="hljs-keyword">implements</span> OnInit {
</span></span><span class='shcb-loc'><span>  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> router: Router,</span>
</span></span><span class='shcb-loc'><span><span class="hljs-params">    <span class="hljs-keyword">private</span> routeDataService: RouteDataService,</span>
</span></span><span class='shcb-loc'><span><span class="hljs-params">    <span class="hljs-keyword">private</span> title: Title</span>) {
</span></span><span class='shcb-loc'><span>  }
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span>  ngOnInit(): <span class="hljs-built_in">void</span> {
</span></span><span class='shcb-loc'><span>    <span class="hljs-keyword">this</span>.router.events
</span></span><span class='shcb-loc'><span>      .pipe(filter(<span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> event <span class="hljs-keyword">instanceof</span> NavigationEnd))
</span></span><span class='shcb-loc'><span>      .subscribe(_ =&gt;
</span></span><mark class='shcb-loc'><span>        <span class="hljs-keyword">this</span>.title.setTitle(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-keyword">this</span>.routeDataService.<span class="hljs-keyword">get</span>()&#91;<span class="hljs-string">"title"</span>]}</span> - Umut Esen`</span>)
</span></mark><span class='shcb-loc'><span>      );
</span></span><span class='shcb-loc'><span>  }
</span></span><span class='shcb-loc'><span>}
</span></span><span class='shcb-loc'><span>
</span></span></code></span></pre>


<p>By using this method, you can set the title of the web page dynamically based on the data from the router events, which will update the title of the window in real-time.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In summary, we learned how to set the page title in Angular. Through DRY principle, we implemented a feature that sets the page title based on Angular router events.</p>



<p>Let me know what you think by dropping a comment below!</p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-set-page-title-based-on-route-in-angular">How to Set Page Title Based on Route in Angular</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/how-to-set-page-title-based-on-route-in-angular/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Generating Routes File for Angular Universal Prerender</title>
		<link>https://onthecode.co.uk/blog/generating-routes-file-for-angular-universal-prerender</link>
					<comments>https://onthecode.co.uk/blog/generating-routes-file-for-angular-universal-prerender#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sat, 07 Jan 2023 19:38:45 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5561</guid>

					<description><![CDATA[<p>In this blog post, I will show you how to generate a routes file for prerendering an Angular Universal application. We will create a basic routes file and append routes dynamically from an XML sitemap ahead of running npm run prerender command when building the application. Pre-requisites This post assumes you already have an Angular Universal application. If this is not the case, add server-side rendering (SSR) capability to your Angular application by following this guide. Once you add SSR, you can use npm run prerender command to prerender your application. Benefits of prerendering Prerendering with Angular Universal refers to the process of rendering an application&#8217;s content on the server side before sending it to the client. This can help improve the performance of an Angular application, especially for users with slow internet connections or on devices with limited resources. By pre-rendering the application&#8217;s initial state on the server and then serving the fully rendered HTML to the client, the client&#8217;s web browser can start rendering the page immediately, rather than having to wait for all of the necessary JavaScript to download and execute before the content is displayed. This can lead to a faster time to first paint and a better user experience overall. Prerender options There are a few build options available to use with prerender command as outlined by official documentation. These options are: A sitemap is likely to have a large number of URLs so we&#8217;ll provide routes using a file. Modify prerender command Open up package.json and update prerender command to use a routes file: There is no need to manually create a routes.txt file because the script we&#8217;re about to write will automatically create it. Generate routes file We will retrieve urls from an XML sitemap using xml-sitemap-url-scraper package. Install this package as a dev dependency so it does not ship with production bundle: Using this package to retrieve URLs is pretty simple, just provide a direct link to your sitemap as shown below. What you&#8217;ll get in return is a promise containing all of the URLs found in the sitemap. Since prerender command expects relative URL separated by a line break in the routes file, we&#8217;re post-processing the results before creating the file routes.txt. You&#8217;ll want to save this script to the root of your project and run using node in the command line: You would ideally run this script as part of your continuous delivery pipeline, before prerendering the application. Your routes.txt will be populated with all the links specified in your sitemap. Conclusion Hopefully this post helped you with prerendering the pages of your Angular application using a routes file. What do you think? Let me know in the comments below!</p>
<p>The post <a href="https://onthecode.co.uk/blog/generating-routes-file-for-angular-universal-prerender">Generating Routes File for Angular Universal Prerender</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this blog post, I will show you how to generate a routes file for prerendering an Angular Universal application. </p>



<p>We will create a basic routes file and append routes dynamically from an XML sitemap ahead of running <code>npm run prerender</code> command when building the application. </p>



<h2 class="wp-block-heading">Pre-requisites </h2>



<p>This post assumes you already have an Angular Universal application. If this is not the case, add server-side rendering (SSR) capability to your Angular application by following this <a href="http://To prerender a static page make sure to add Server-Side Rendering (SSR) capabilities to your application. For more information see the universal guide. Once SSR is added, run the following command:" target="_blank" rel="noreferrer noopener">guide</a>.</p>



<p>Once you add SSR, you can use <code>npm run prerender</code> command to prerender your application.</p>



<h2 class="wp-block-heading">Benefits of prerendering</h2>



<p>Prerendering with Angular Universal refers to the process of rendering an application&#8217;s content on the server side before sending it to the client. </p>



<p>This can help improve the performance of an Angular application, especially for users with slow internet connections or on devices with limited resources.</p>



<p>By pre-rendering the application&#8217;s initial state on the server and then serving the fully rendered HTML to the client, the client&#8217;s web browser can start rendering the page immediately, rather than having to wait for all of the necessary JavaScript to download and execute before the content is displayed. </p>



<p>This can lead to a faster time to first paint and a better user experience overall.</p>



<h2 class="wp-block-heading">Prerender options</h2>



<p>There are a few build options available to use with <code>prerender</code> command as outlined by <a href="https://angular.io/guide/prerendering#build-options-for-prerendering" target="_blank" rel="noreferrer noopener">official documentation</a>.</p>



<p>These options are:</p>



<ul class="wp-block-list">
<li>Provide extra routes in the command line</li>



<li>Provide routes using a file</li>



<li>Prerender specific routes</li>
</ul>



<p>A sitemap is likely to have a large number of URLs so we&#8217;ll provide routes using a file.</p>



<h2 class="wp-block-heading">Modify prerender command</h2>



<p>Open up <code>package.json</code> and update prerender command to use a routes file:</p>


<pre class="wp-block-code"><span><code class="hljs language-json"><span class="hljs-string">"prerender"</span>: <span class="hljs-string">"ng run myapp:prerender --routes-file routes.txt"</span></code></span></pre>


<p>There is no need to manually create a routes.txt file because the script we&#8217;re about to write will automatically create it.</p>



<h2 class="wp-block-heading">Generate routes file</h2>



<p>We will retrieve urls from an XML sitemap using <code>xml-sitemap-url-scraper</code> package.</p>



<p>Install this package as a dev dependency so it does not ship with production bundle:</p>


<pre class="wp-block-code"><span><code class="hljs language-bash">npm install xml-sitemap-url-scraper --save-dev</code></span></pre>


<p>Using this package to retrieve URLs is pretty simple, just provide a direct link to your sitemap as shown below. </p>



<p>What you&#8217;ll get in return is a promise containing all of the URLs found in the sitemap.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">const</span> { sitemapUrlScraper } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"xml-sitemap-url-scraper"</span>);
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">const</span> url = <span class="hljs-string">"https://mysite.com/sitemap_index.xml"</span>;
</span></span><span class='shcb-loc'><span>
</span></span><mark class='shcb-loc'><span>sitemapUrlScraper(&#91;url])
</span></mark><span class='shcb-loc'><span>    .then(<span class="hljs-function"><span class="hljs-params">urls</span> =&gt;</span> {
</span></span><span class='shcb-loc'><span>        <span class="hljs-keyword">const</span> routes = urls
</span></span><mark class='shcb-loc'><span>            .map(<span class="hljs-function"><span class="hljs-params">url</span> =&gt;</span> url.replace(<span class="hljs-keyword">new</span> URL(url).origin, <span class="hljs-string">""</span>))
</span></mark><mark class='shcb-loc'><span>            .join(<span class="hljs-string">'\r\n'</span>);
</span></mark><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span>        fs.writeFile(<span class="hljs-string">'routes.txt'</span>, <span class="hljs-string">'\r\n'</span> + routes, err =&gt; {
</span></span><span class='shcb-loc'><span>            <span class="hljs-keyword">if</span> (err) {
</span></span><span class='shcb-loc'><span>                <span class="hljs-built_in">console</span>.error(err);
</span></span><span class='shcb-loc'><span>            }
</span></span><span class='shcb-loc'><span>        });
</span></span><span class='shcb-loc'><span>    })
</span></span><span class='shcb-loc'><span>    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { <span class="hljs-built_in">console</span>.log(err); })
</span></span></code></span></pre>


<p>Since <code>prerender</code> command expects relative URL separated by a line break in the routes file, we&#8217;re post-processing the results before creating the file <code>routes.txt</code>.</p>



<p>You&#8217;ll want to save this script to the root of your project and run using node in the command line:</p>


<pre class="wp-block-code"><span><code class="hljs language-bash">node route-fetcher.js

Processing XML Sitemap:  https://mysite.com/sitemap_index.xml
Processing XML Sitemap:  https://mysite.com/post-sitemap.xml
Processing XML Sitemap:  https://mysite.com/page-sitemap.xml
Processing XML Sitemap:  https://mysite.com/category-sitemap.xml</code></span></pre>


<p>You would ideally run this script as part of your continuous delivery pipeline, <strong>before</strong> prerendering the application.</p>



<p>Your routes.txt will be populated with all the links specified in your sitemap.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Hopefully this post helped you with prerendering the pages of your Angular application using a routes file. </p>



<p>What do you think? Let me know in the comments below!</p>
<p>The post <a href="https://onthecode.co.uk/blog/generating-routes-file-for-angular-universal-prerender">Generating Routes File for Angular Universal Prerender</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/generating-routes-file-for-angular-universal-prerender/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fixing Angular Unit Tests: Cannot read property &#8216;range&#8217; of undefined</title>
		<link>https://onthecode.co.uk/blog/fixing-angular-unit-tests-cannot-read-property-range-of-undefined</link>
					<comments>https://onthecode.co.uk/blog/fixing-angular-unit-tests-cannot-read-property-range-of-undefined#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Mon, 19 Dec 2022 15:22:27 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5483</guid>

					<description><![CDATA[<p>While upgrading Node from v12 to v16, I came across a problem with Angular unit tests where an exception would stop the test run with error Cannot read property 'range' of undefined. In this post, I&#8217;ll explain the steps I took to identify the root cause of issue and propose potential solutions. Identifying the root cause The exception stack trace hints at the root cause of this issue: Let&#8217;s dig deeper and find out what&#8217;s going on the line of code throwing this exception: It looks like webpack-dev-middleware is handling requests as part of the test run. When it comes to handling headers on the request, it is falling over with: Clearly, Accept-Ranges headers are not present in some requests performed during our test run. In order to pinpoint which request is causing this error, let&#8217;s output the name of each file during the test run: Run tests again with ng test and see the file name causing this issue: At this point, we can see the file name and this should hopefully be familiar to you. The chances are your project is somehow trying to load this file from the assets folder using a relative path. Let&#8217;s look at what we can do to fix this issue. Fix #1 &#8211; Configure karma to use proxy The very first thing I tried to fix this issue was to follow the advice of Ievgen, who had the same problem within an Angular project inside a docker container. Simply add the following code in karma.conf.js after&#160;config.set({ Ievgen suggests this new rule in karma configuration will point all requests matching /assets/ to the base folder of the project. Unfortunately, this did not work for me even after adjusting the path to match the setup of my project. Although Ievgen&#8217;s solution did not work for me, it put me in the right direction and helped identify the following fixes. Fix #2 &#8211; Stop using relative paths The first thing I did was to find all the usages of assets folder in the entire source code. It turned out some css files were using relative paths to load some images from the assets folder: The fix is to define the path from the src folder: Repeat this for all references of assets folder to ensure all paths correctly identify a file. Fix #3 &#8211; Exclude 3rd party stylesheets during test run There may be external packages included in the test configuration within angular.json that are using relative path to assets folder. As you can see in the above snippet, the test configuration is loading styles from an external package. Since this package is internally using relative paths to assets, folder the exception is thrown. The solution is to remove this line of code to exclude 3rd party stylesheets during the test run. I hope you found this post useful, drop a comment below to let me know what you think!</p>
<p>The post <a href="https://onthecode.co.uk/blog/fixing-angular-unit-tests-cannot-read-property-range-of-undefined">Fixing Angular Unit Tests: Cannot read property &#8216;range&#8217; of undefined</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>While upgrading Node from v12 to v16, I came across a problem with <a href="/blog/category/angular" target="_blank" rel="noreferrer noopener">Angular </a>unit tests where an exception would stop the test run with error <code>Cannot read property 'range' of undefined</code>.</p>



<p>In this post, I&#8217;ll explain the steps I took to identify the root cause of issue and propose potential solutions.</p>



<h2 class="wp-block-heading">Identifying the root cause</h2>



<p>The exception stack trace hints at the root cause of this issue:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript shcb-code-table"><span class='shcb-loc'><span>(Windows <span class="hljs-number">8.1</span><span class="hljs-number">.0</span><span class="hljs-number">.0</span>): Executed <span class="hljs-number">9</span> <span class="hljs-keyword">of</span> <span class="hljs-number">846</span>‌ SUCCESS‌ (<span class="hljs-number">0</span> secs &amp;#x2F; <span class="hljs-number">1.912</span> secs)‌
</span></span><mark class='shcb-loc'><span><span class="hljs-number">15</span> <span class="hljs-number">12</span> <span class="hljs-number">2022</span> <span class="hljs-number">15</span>:<span class="hljs-number">14</span>:<span class="hljs-number">23.895</span>:ERROR &#91;karma-server]: ‌<span class="hljs-built_in">TypeError</span>: Cannot read properties <span class="hljs-keyword">of</span> <span class="hljs-literal">undefined</span> (reading <span class="hljs-string">'range'</span>)‌
</span></mark><span class='shcb-loc'><span>    at handleRangeHeaders (D:\Agents\<span class="hljs-number">1</span>\_work\<span class="hljs-number">424</span>\s\MyApp.Web\node_modules\webpack-dev-middleware\lib\util.js:<span class="hljs-number">134</span>:<span class="hljs-number">21</span>)
</span></span><span class='shcb-loc'><span>    at processRequest (D:\Agents\<span class="hljs-number">1</span>\_work\<span class="hljs-number">424</span>\s\MyApp.Web\node_modules\webpack-dev-middleware\lib\middleware.js:<span class="hljs-number">98</span>:<span class="hljs-number">19</span>)
</span></span><span class='shcb-loc'><span>    at ready (D:\Agents\<span class="hljs-number">1</span>\_work\<span class="hljs-number">424</span>\s\MyApp.Web\node_modules\webpack-dev-middleware\lib\util.js:<span class="hljs-number">54</span>:<span class="hljs-number">12</span>)
</span></span><span class='shcb-loc'><span>    at handleRequest (D:\Agents\<span class="hljs-number">1</span>\_work\<span class="hljs-number">424</span>\s\MyApp.Web\node_modules\webpack-dev-middleware\lib\util.js:<span class="hljs-number">185</span>:<span class="hljs-number">5</span>)
</span></span><span class='shcb-loc'><span>    at D:\Agents\<span class="hljs-number">1</span>\_work\<span class="hljs-number">424</span>\s\MyApp.Web\node_modules\webpack-dev-middleware\lib\middleware.js:<span class="hljs-number">64</span>:<span class="hljs-number">7</span>
</span></span><span class='shcb-loc'><span>    at <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span> (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">anonymous</span>&gt;</span>)</span>
</span></span></code></span></pre>


<p>Let&#8217;s dig deeper and find out what&#8217;s going on the line of code throwing this exception:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-comment">// node_modules\webpack-dev-middleware\lib\util.js:134 </span>
</span></span><span class='shcb-loc'><span>handleRangeHeaders(content, req, res) {
</span></span><span class='shcb-loc'><span>    <span class="hljs-comment">// assumes express API. For other servers, need to add logic to access</span>
</span></span><span class='shcb-loc'><span>    <span class="hljs-comment">// alternative header APIs</span>
</span></span><span class='shcb-loc'><span>    res.setHeader(<span class="hljs-string">'Accept-Ranges'</span>, <span class="hljs-string">'bytes'</span>);
</span></span><span class='shcb-loc'><span>
</span></span><mark class='shcb-loc'><span>    <span class="hljs-keyword">if</span> (req.headers.range) {
</span></mark><span class='shcb-loc'><span>      <span class="hljs-keyword">const</span> ranges = parseRange(content.length, req.headers.range);
</span></span></code></span></pre>


<p>It looks like <code>webpack-dev-middleware</code> is handling requests as part of the test run. When it comes to handling headers on the request, it is falling over with:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">Cannot read properties <span class="hljs-keyword">of</span> <span class="hljs-literal">undefined</span> (reading <span class="hljs-string">'range'</span>)‌</code></span></pre>


<p>Clearly, <code>Accept-Ranges</code> headers are not present in some requests performed during our test run.</p>



<p>In order to pinpoint which request is causing this error, let&#8217;s output the name of each file during the test run:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// node_modules\webpack-dev-middleware\lib\util.js:134 </span>
  handleRangeHeaders(content, req, res) {
    <span class="hljs-built_in">console</span>.log(req.url);</code></span></pre>


<p>Run tests again with <code>ng test</code> and see the file name causing this issue:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">/_karma_webpack_/assets/icons/icon-library.svg
<span class="hljs-number">15</span> <span class="hljs-number">12</span> <span class="hljs-number">2022</span> <span class="hljs-number">15</span>:<span class="hljs-number">14</span>:<span class="hljs-number">23.895</span>:ERROR &#91;karma-server]: ‌<span class="hljs-built_in">TypeError</span>: Cannot read properties <span class="hljs-keyword">of</span> <span class="hljs-literal">undefined</span> (reading <span class="hljs-string">'range'</span>)‌</code></span></pre>


<p></p>



<p>At this point, we can see the file name and this should hopefully be familiar to you. The chances are your project is somehow trying to load this file from the assets folder using a relative path.</p>



<p>Let&#8217;s look at what we can do to fix this issue.</p>



<h2 class="wp-block-heading">Fix #1 &#8211; Configure karma to use proxy</h2>



<p>The very first thing I tried to fix this issue was to follow the advice of <a href="https://ievgen.de/2020/11/17/angular-tests-fail-docker/" target="_blank" rel="noreferrer noopener">Ievgen</a>, who had the same problem within an Angular project inside a docker container. </p>



<p>Simply add the following code in <em>karma.conf.js</em> after&nbsp;<code>config.set({</code></p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">proxies: {
    <span class="hljs-string">'/assets/'</span>: <span class="hljs-string">'/base/src/assets/'</span>
},</code></span></pre>


<p>Ievgen suggests this new rule in karma configuration will point all requests matching <code>/assets/</code> to the base folder of the project. Unfortunately, this did not work for me even after adjusting the path to match the setup of my project. </p>



<p>Although Ievgen&#8217;s solution did not work for me, it put me in the right direction and helped identify the following fixes. </p>



<h2 class="wp-block-heading">Fix #2 &#8211; Stop using relative paths</h2>



<p>The first thing I did was to find all the usages of <code>assets</code> folder in the entire source code. </p>



<p>It turned out some <code>css</code> files were using relative paths to load some images from the assets folder:</p>


<pre class="wp-block-code"><span><code class="hljs">  content: url(../../../assets/icons/back-icon.png);
</code></span></pre>


<p>The fix is to define the path from the src folder:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript">  content: url(<span class="hljs-string">"/src/assets/icons/back-icon.png"</span>);
</code></span></pre>


<p>Repeat this for all references of assets folder to ensure all paths correctly identify a file.</p>



<h2 class="wp-block-heading">Fix #3 &#8211; Exclude 3rd party stylesheets during test run</h2>



<p>There may be external packages included in the test configuration within <code>angular.json</code> that are using relative path to assets folder.</p>


<pre class="wp-block-code"><span><code class="hljs language-json shcb-code-table"><span class='shcb-loc'><span><span class="hljs-comment">// angular.json </span>
</span></span><span class='shcb-loc'><span><span class="hljs-string">"test"</span>: {
</span></span><span class='shcb-loc'><span>          <span class="hljs-attr">"builder"</span>: <span class="hljs-string">"@angular-devkit/build-angular:karma"</span>,
</span></span><span class='shcb-loc'><span>          <span class="hljs-attr">"options"</span>: {
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"codeCoverage"</span>: <span class="hljs-literal">true</span>,
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"main"</span>: <span class="hljs-string">"src/test.ts"</span>,
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"polyfills"</span>: <span class="hljs-string">"src/polyfills.ts"</span>,
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"tsConfig"</span>: <span class="hljs-string">"src/tsconfig.spec.json"</span>,
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"karmaConfig"</span>: <span class="hljs-string">"karma.conf.js"</span>,
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"styles"</span>: &#91;
</span></span><span class='shcb-loc'><span>              <span class="hljs-string">"src/styles.css"</span>
</span></span><mark class='shcb-loc'><span>              <span class="hljs-string">"node_modules/@my-company/web-styles/sass/main.scss"</span>
</span></mark><span class='shcb-loc'><span>            ],
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"scripts"</span>: &#91;],
</span></span><span class='shcb-loc'><span>            <span class="hljs-attr">"assets"</span>: &#91;
</span></span><span class='shcb-loc'><span>              <span class="hljs-string">"src/assets"</span>,
</span></span><span class='shcb-loc'><span>              <span class="hljs-string">"src/Web.config"</span>,
</span></span><span class='shcb-loc'><span>              <span class="hljs-string">"src/auth.config"</span>
</span></span><span class='shcb-loc'><span>            ]
</span></span><span class='shcb-loc'><span>          } 
</span></span></code></span></pre>


<p>As you can see in the above snippet, the test configuration is loading styles from an external package.</p>



<p>Since this package is internally using relative paths to assets, folder the exception is thrown. The solution is to remove this line of code to exclude 3rd party stylesheets during the test run.</p>



<p>I hope you found this post useful, drop a comment below to let me know what you think!</p>
<p>The post <a href="https://onthecode.co.uk/blog/fixing-angular-unit-tests-cannot-read-property-range-of-undefined">Fixing Angular Unit Tests: Cannot read property &#8216;range&#8217; of undefined</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/fixing-angular-unit-tests-cannot-read-property-range-of-undefined/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Angular Universal: Setting HTTP Status Code</title>
		<link>https://onthecode.co.uk/blog/angular-universal-setting-http-status-code</link>
					<comments>https://onthecode.co.uk/blog/angular-universal-setting-http-status-code#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Tue, 29 Nov 2022 23:17:51 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5443</guid>

					<description><![CDATA[<p>Angular Universal gives superpowers to traditional Angular apps such as server-side rendering (SSR) and full features using Express.js server. This allows us to implement features like returning HTTP status codes in appropriate scenarios. In this post, I will show you how to set the HTTP status code from an Angular application with SSR. Background Let&#8217;s address why you might even want to set HTTP status code from an Angular component in the first place. As an example, my application renders the following component when it does not recognise a URL: When the component is rendered in the browser, the status code is actually 200 OK. Search engines would consider this response as valid and continue indexing the contents of this page. In this case, we should be returning the correct status code: 404 Not Found. Another possible scenario is returning status code 401 Unauhorised when securing pages from anonymous access. Inject response from Express.js Like any other server-side application, we need to modify the HTTP response to set the status code. To do this in Angular Universal, we can inject the Response object from Express.js server into the constructor of the component: Notice the dependency is optional since Angular Universal applications run on both the server and the browser. An optional parameter becomes null when the application is running in the browser. This means any usage of the response should be protected with a null guard. Setting the status code With the response available in the component, we can implement our logic inside the OnInit event. We can pass in the status code to the status method as shown below as per Response API docs. Since the response can be null in the browser context, we guard against null value to avoid our component from failing. Let&#8217;s now serve an SSR build locally to test the status code. Running the same scenario now yields 404 Not Found response in the browser. Full source code Putting it all together this is how the component looks like now: Unit tests It helps to put in unit test coverage around the features of the component to act as a safety net. Tests also help document our code. This is the full spec file containing the implementation details for all of the tests:</p>
<p>The post <a href="https://onthecode.co.uk/blog/angular-universal-setting-http-status-code">Angular Universal: Setting HTTP Status Code</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Angular Universal gives superpowers to traditional Angular apps such as server-side rendering (SSR) and full features using Express.js server. This allows us to implement features like returning HTTP status codes in appropriate scenarios. </p>



<p>In this post, I will show you how to set the HTTP status code from an Angular application with SSR.</p>



<h2 class="wp-block-heading">Background</h2>



<p>Let&#8217;s address why you might even want to set HTTP status code from an Angular component in the first place.</p>



<p>As an example, my application renders the following component when it does not recognise a URL:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-not-found-page'</span>,
  template: <span class="hljs-string">`
      &lt;h1&gt;Not Found&lt;/h1&gt;
      &lt;p&gt;This page does not exist.&lt;/p&gt;
  `</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NotFoundPageComponent {}</code></span></pre>


<p>When the component is rendered in the browser, the status code is actually <code>200 OK</code>. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img fetchpriority="high" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-27-at-15.12.27-1024x654.png" alt="Not Found 200 OK" class="wp-image-5444" width="512" height="327" srcset="https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-27-at-15.12.27-1024x654.png 1024w, https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-27-at-15.12.27-300x192.png 300w, https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-27-at-15.12.27-768x491.png 768w, https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-27-at-15.12.27.png 1236w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption>Not Found 200 OK</figcaption></figure></div>


<p>Search engines would consider this response as valid and continue indexing the contents of this page. </p>



<p>In this case, we should be returning the correct status code: <code>404 Not Found</code>.</p>



<p>Another possible scenario is returning status code <code>401 Unauhorised</code> when securing pages from anonymous access. </p>



<h2 class="wp-block-heading">Inject response from Express.js</h2>



<p>Like any other server-side application, we need to modify the HTTP response to set the status code.</p>



<p>To do this in Angular Universal, we can inject the <code>Response</code> object from Express.js server into the constructor of the component:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { Component, Inject, Optional } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { RESPONSE } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nguniversal/express-engine/tokens'</span>
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">import</span> { Response } <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>
</span></span><span class='shcb-loc'><span><span class="hljs-meta">@Component</span>({
</span></span><span class='shcb-loc'><span>  selector: <span class="hljs-string">'app-not-found-page'</span>,
</span></span><span class='shcb-loc'><span>  template: <span class="hljs-string">`</span>
</span></span><span class='shcb-loc'><span><span class="hljs-string">      &lt;h1&gt;Not Found&lt;/h1&gt;</span>
</span></span><span class='shcb-loc'><span><span class="hljs-string">      &lt;p&gt;This page does not exist.&lt;/p&gt;</span>
</span></span><span class='shcb-loc'><span><span class="hljs-string">  `</span>
</span></span><span class='shcb-loc'><span>})
</span></span><span class='shcb-loc'><span><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NotFoundPageComponent {
</span></span><span class='shcb-loc'><span>  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>
</span></span><mark class='shcb-loc'><span><span class="hljs-params">    <span class="hljs-meta">@Optional</span>() <span class="hljs-meta">@Inject</span>(RESPONSE) <span class="hljs-keyword">private</span> response: Response</span>
</span></mark><span class='shcb-loc'><span><span class="hljs-params">  </span>) { }
</span></span><span class='shcb-loc'><span>}
</span></span></code></span></pre>


<p>Notice the dependency is optional since Angular Universal applications run on both the server and the browser.</p>



<p>An optional parameter becomes null when the application is running in the browser. This means any usage of the <code>response</code> should be protected with a null guard.</p>



<h2 class="wp-block-heading">Setting the status code</h2>



<p>With the response available in the component, we can implement our logic inside the <code>OnInit</code> event.</p>



<p>We can pass in the status code to the <code>status</code> method as shown below as per Response API <a href="https://expressjs.com/en/api.html#res.status" target="_blank" rel="noreferrer noopener">docs</a>. </p>


<pre class="wp-block-code"><span><code class="hljs language-typescript shcb-code-table"><span class='shcb-loc'><span><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NotFoundPageComponent <span class="hljs-keyword">implements</span> OnInit {
</span></span><span class='shcb-loc'><span>  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>
</span></span><span class='shcb-loc'><span><span class="hljs-params">    <span class="hljs-meta">@Optional</span>() <span class="hljs-meta">@Inject</span>(RESPONSE) <span class="hljs-keyword">private</span> response: Response</span>
</span></span><span class='shcb-loc'><span><span class="hljs-params">  </span>) { }
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span>  ngOnInit() {
</span></span><span class='shcb-loc'><span>    <span class="hljs-comment">// Return 404 when running server side</span>
</span></span><span class='shcb-loc'><span>    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.response) {
</span></span><mark class='shcb-loc'><span>      <span class="hljs-keyword">this</span>.response.status(<span class="hljs-number">404</span>);
</span></mark><span class='shcb-loc'><span>    }
</span></span><span class='shcb-loc'><span>  }
</span></span><span class='shcb-loc'><span>}
</span></span></code></span></pre>


<p>Since the response can be null in the browser context, we guard against null value to avoid our component from failing.</p>



<p>Let&#8217;s now serve an SSR build locally to test the status code.</p>


<pre class="wp-block-code"><span><code class="hljs language-bash">npm run build:ssr
npm run serve:ssr</code></span></pre>


<p>Running the same scenario now yields <code>404 Not Found</code> response in the browser.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-29-at-22.52.12-1.png" alt="Not Found 404" class="wp-image-5456" width="506" height="393" srcset="https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-29-at-22.52.12-1.png 1012w, https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-29-at-22.52.12-1-300x233.png 300w, https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-29-at-22.52.12-1-768x596.png 768w" sizes="(max-width: 506px) 100vw, 506px" /><figcaption>Not Found 404</figcaption></figure></div>


<h2 class="wp-block-heading">Full source code</h2>



<p>Putting it all together this is how the component looks like now:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">import</span> { Component, Inject, OnInit, Optional } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { RESPONSE } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nguniversal/express-engine/tokens'</span>
<span class="hljs-keyword">import</span> { Response } <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-not-found-page'</span>,
  template: <span class="hljs-string">`
      &lt;h1&gt;Not Found&lt;/h1&gt;
      &lt;p&gt;This page does not exist.&lt;/p&gt;
  `</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NotFoundPageComponent <span class="hljs-keyword">implements</span> OnInit {

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">
    <span class="hljs-meta">@Optional</span>() <span class="hljs-meta">@Inject</span>(RESPONSE) <span class="hljs-keyword">private</span> response: Response
  </span>) { }

  ngOnInit() {
    <span class="hljs-comment">// Return 404 when running server side</span>
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.response) {
      <span class="hljs-keyword">this</span>.response.status(<span class="hljs-number">404</span>);
    }
  }
}</code></span></pre>


<h2 class="wp-block-heading">Unit tests</h2>



<p>It helps to put in unit test coverage around the features of the component to act as a safety net. Tests also help document our code. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-29-at-23.04.53.png" alt="" class="wp-image-5461" width="346" height="120" srcset="https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-29-at-23.04.53.png 692w, https://onthecode.co.uk/wp-content/uploads/2022/11/Screenshot-2022-11-29-at-23.04.53-300x104.png 300w" sizes="(max-width: 346px) 100vw, 346px" /></figure></div>


<p>This is the full <code>spec</code> file containing the implementation details for all of the tests:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">import</span> { ComponentFixture, TestBed } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core/testing'</span>;

<span class="hljs-keyword">import</span> { NotFoundPageComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./not-found-page.component'</span>;
<span class="hljs-keyword">import</span> { RESPONSE } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nguniversal/express-engine/tokens'</span>;
<span class="hljs-keyword">import</span> { By } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;

describe(<span class="hljs-string">'NotFoundPageComponent'</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-keyword">let</span> component: NotFoundPageComponent;
  <span class="hljs-keyword">let</span> fixture: ComponentFixture&lt;NotFoundPageComponent&gt;;
  <span class="hljs-keyword">let</span> response: <span class="hljs-built_in">any</span>;

  describe(<span class="hljs-string">'client-side'</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
    beforeEach(<span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">await</span> TestBed.configureTestingModule({
        declarations: &#91;NotFoundPageComponent],
        providers: &#91;
          {
            provide: RESPONSE,
            useValue: <span class="hljs-literal">null</span>
          }
        ]
      })
        .compileComponents();

      fixture = TestBed.createComponent(NotFoundPageComponent);
      component = fixture.componentInstance;
      response = TestBed.inject(RESPONSE);
      fixture.detectChanges();
    });

    it(<span class="hljs-string">'should create'</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
      expect(component).toBeTruthy();
    });

    it(<span class="hljs-string">'should render elements'</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
      expect(fixture.debugElement.query(By.css(<span class="hljs-string">"h1"</span>)).nativeElement.textContent).toEqual(<span class="hljs-string">"Not Found"</span>);
      expect(fixture.debugElement.query(By.css(<span class="hljs-string">"p"</span>)).nativeElement.textContent).toEqual(<span class="hljs-string">"This page does not exist."</span>);
    });
  });

  describe(<span class="hljs-string">'server-side'</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
    beforeEach(<span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">await</span> TestBed.configureTestingModule({
        declarations: &#91;NotFoundPageComponent],
        providers: &#91;
          {
            provide: RESPONSE,
            useValue: jasmine.createSpyObj(<span class="hljs-string">"Response"</span>, &#91;<span class="hljs-string">"status"</span>])
          }
        ]
      })
        .compileComponents();

      fixture = TestBed.createComponent(NotFoundPageComponent);
      component = fixture.componentInstance;
      response = TestBed.inject(RESPONSE);
      fixture.detectChanges();
    });

    it(<span class="hljs-string">'should set 404 status code on response'</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
      expect(response.status).toHaveBeenCalledOnceWith(<span class="hljs-number">404</span>);
    });
  });

});
</code></span></pre><p>The post <a href="https://onthecode.co.uk/blog/angular-universal-setting-http-status-code">Angular Universal: Setting HTTP Status Code</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/angular-universal-setting-http-status-code/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Error: Cannot resolve type entity i3.DialogModule to symbol</title>
		<link>https://onthecode.co.uk/blog/error-cannot-resolve-type-entity-i3-dialogmodule-to-symbol</link>
					<comments>https://onthecode.co.uk/blog/error-cannot-resolve-type-entity-i3-dialogmodule-to-symbol#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sun, 11 Sep 2022 09:56:00 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=5226</guid>

					<description><![CDATA[<p>While updating my Angular Material Starter Template to Angular 14, I ran into an error causing broken builds. The console output seems to suggest this is a problem with Dialog module from Angular Component Dev Kit (CDK): Cannot resolve type entity i3.DialogModule to symbol. After hours of research online with no luck, it turns out I never had @angular/cdk as a dependency in the project. I found this out by checking the getting started section of Angular Material docs. How to fix Error: Cannot resolve type entity i3.DialogModule to symbol: Open up package.json file Add @angular/cdk to dependencies section: Run npm install to update download the new package It doesn&#8217;t matter where you put the new dependency, as long as it is within the dependencies block. One thing to watch out for is using the correct version &#8211; it must match the rest of the Angular packages. In the code snippet below, you can see I am using version ^14.2.1 because all other angular packages are on this version. I hope this post helped you solve this problem! It is really not clear to my why I didn&#8217;t have this error in Angular 13. After all, a missing dependency should break builds, right? Let me know in the comments, if you know why.</p>
<p>The post <a href="https://onthecode.co.uk/blog/error-cannot-resolve-type-entity-i3-dialogmodule-to-symbol">Error: Cannot resolve type entity i3.DialogModule to symbol</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>While updating my <a href="https://onthecode.co.uk/angular-material-starter-template-for-your-next-project/">Angular Material Starter Template</a> to Angular 14, I ran into an error causing broken builds. The console output seems to suggest this is a problem with <code>Dialog</code> module from Angular <a href="https://material.angular.io/cdk/categories" target="_blank" rel="noreferrer noopener">Component Dev Kit (CDK)</a>: Cannot resolve type entity i3.DialogModule to symbol.</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript shcb-code-table"><span class='shcb-loc'><span>./src/polyfills.ts - <span class="hljs-built_in">Error</span>: Module build failed (<span class="hljs-keyword">from</span> ./node_modules/@ngtools/webpack/src/ivy/index.js):
</span></span><mark class='shcb-loc'><span><span class="hljs-built_in">Error</span>: Cannot resolve type entity i3.DialogModule to symbol
</span></mark><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span><span class="hljs-attr">Error</span>: node_modules/@angular/material/dialog/index.d.ts:<span class="hljs-number">3</span>:<span class="hljs-number">36</span> - error TS2307: Cannot find <span class="hljs-built_in">module</span> <span class="hljs-string">'@angular/cdk/dialog'</span> or its corresponding type declarations.
</span></span><span class='shcb-loc'><span>
</span></span><span class='shcb-loc'><span><span class="hljs-number">3</span> <span class="hljs-keyword">import</span> { CdkDialogContainer } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/cdk/dialog'</span>;
</span></span></code></span></pre>


<p>After hours of research online with no luck, it turns out I never had <code>@angular/cdk</code> as a dependency in the project. </p>



<p>I found this out by checking the getting started section of <a href="http://material.angular.io" target="_blank" rel="noreferrer noopener">Angular Material docs</a>.</p>



<p>How to fix <strong>Error: Cannot resolve type entity i3.DialogModule to symbol</strong>:</p>



<ol class="wp-block-list"><li>Open up <code>package.json</code> file </li><li>Add <code>@angular/cdk</code> to dependencies section:</li><li>Run <code>npm install</code> to update download the new package</li></ol>



<p>It doesn&#8217;t matter where you put the new dependency, as long as it is within the dependencies block. </p>



<p>One thing to watch out for is using the correct version &#8211; it must match the rest of the Angular packages. </p>



<p>In the code snippet below, you can see I am using version <code>^14.2.1</code> because all other angular packages are on this version. </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript shcb-code-table"><span class='shcb-loc'><span>  ....
</span></span><span class='shcb-loc'><span>  <span class="hljs-string">"dependencies"</span>: {
</span></span><span class='shcb-loc'><span>    <span class="hljs-string">"@angular/animations"</span>: <span class="hljs-string">"^14.2.1"</span>,
</span></span><span class='shcb-loc'><span>    <span class="hljs-string">"@angular/common"</span>: <span class="hljs-string">"^14.2.1"</span>,
</span></span><span class='shcb-loc'><span>    <span class="hljs-string">"@angular/compiler"</span>: <span class="hljs-string">"^14.2.1"</span>,
</span></span><span class='shcb-loc'><span>    <span class="hljs-string">"@angular/core"</span>: <span class="hljs-string">"^14.2.1"</span>,
</span></span><mark class='shcb-loc'><span>    <span class="hljs-string">"@angular/cdk"</span>: <span class="hljs-string">"^14.2.1"</span>,
</span></mark><span class='shcb-loc'><span>    ...
</span></span><span class='shcb-loc'><span>  }
</span></span><span class='shcb-loc'><span>  ...
</span></span></code></span></pre>


<p>I hope this post helped you solve this problem!</p>



<p>It is really not clear to my why I didn&#8217;t have this error in Angular 13. After all, a missing dependency should break builds, right? Let me know in the comments, if you know why.</p>
<p>The post <a href="https://onthecode.co.uk/blog/error-cannot-resolve-type-entity-i3-dialogmodule-to-symbol">Error: Cannot resolve type entity i3.DialogModule to symbol</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/error-cannot-resolve-type-entity-i3-dialogmodule-to-symbol/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
