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

<channel>
	<title>angular injection token feature &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/angular-injection-token-feature/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Fri, 19 Aug 2022 04:25:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>angular injection token feature &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Angular InjectionToken Feature</title>
		<link>https://topreviewhostingasp.net/angular-injectiontoken-feature/</link>
					<comments>https://topreviewhostingasp.net/angular-injectiontoken-feature/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 19 Aug 2022 04:21:33 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular injection token]]></category>
		<category><![CDATA[angular injection token feature]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[angular tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3139</guid>

					<description><![CDATA[In this article, I want to talk about a feature which Angular provides, that isn’t particularly well known or used by many developers. When using Angular InjectionToken, we can specify a factory function which returns a default value of the parameterized type T. For example: This sets up the InjectionToken using this factory as a provider, as if it was defined [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this article, I want to talk about a feature which Angular provides, that isn’t particularly well known or used by many developers. When using Angular <code>InjectionToken</code>, we can specify a <strong>factory</strong> function which returns a default value of the parameterized type <code>T</code>. For example:</p>



<pre class="wp-block-code"><code>const WINDOW = new InjectionToken&lt;Window&gt;('A reference to the window object', {
  factory: () =&gt; window,
});</code></pre>



<p>This sets up the <code><a href="https://angular.io/api/core/InjectionToken" target="_blank" rel="noreferrer noopener">InjectionToken</a></code> using this factory as a provider, as if it was defined explicitly in the application’s root injector. Now we can use it anywhere in our application:</p>



<pre class="wp-block-code"><code>@Component({
  selector: 'my-app'
})
export class AppComponent {
  constructor(@Inject(WINDOW) window: Window) {}
}</code></pre>



<p>But that’s not all. We can use the <code><a href="https://angular.io/api/core/inject#inject" target="_blank" rel="noreferrer noopener">inject</a></code> function to obtain a reference to other providers inside our <code>factory</code> function. Let’s see another real-world example:</p>



<pre class="wp-block-code"><code>import { inject, InjectionToken } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

export type TimespanProvider = Observable&lt;string&gt;;

export const TIMESPAN = new InjectionToken('Subscribe to timespan query param', {
  factory() {
    const activatedRoute = inject(ActivatedRoute);

    return activatedRoute.queryParams.pipe(
      pluck('timespan'),
      filterNil(),
      distinctUntilChanged()
    );
  },
});</code></pre>



<p>In the above example, we inject the <code>ActivatedRoute</code> provider and return an observable for the <code>timespan</code> query param. Now we can use it in our components:</p>



<pre class="wp-block-code"><code>@Component({
  selector: 'app-home'
})
export class HomeComponent implements OnInit {
  constructor(@Inject(TIMESPAN) private timespan$: TimespanProvider) {}

  ngOnInit() {
    this.timespan$.pipe(untilDestroyed(this)).subscribe(console.log);
  }
}</code></pre>



<p>We can also pass <code>InjectionFlags</code> to the inject function. For example, we can say that the requested provider is <code>optional</code>:</p>



<pre class="wp-block-code"><code>import { inject, InjectionToken, InjectFlags } from '@angular/core';

const MY_PROVIDER = new InjectionToken('', {
  factory: () =&gt; {
    const optional = inject(SomeProvider, InjectFlags.Optional);
    
    return optional ?? fallback;
  },
});</code></pre>



<p>Here’s another real-world example — let’s say you have a theme service, which exposes the current user’s theme:</p>



<pre class="wp-block-code"><code>@Injectable({ providedIn: 'root' })
export class ThemeService {
  private theme = new Subject&lt;string&gt;();
  theme$ = this.theme.asObservable();

  setTheme(theme: string) {
    this.theme.next(theme);
  }
}</code></pre>



<p>The only data that most components need is the current theme. So instead of doing the following in each component:</p>



<pre class="wp-block-code"><code>@Component({
  selector: 'app-hello',
  template: `&lt;h1&gt;{{ theme$ | async }}&lt;/h1&gt;`
})
export class HelloComponent {
  theme$: Observable&lt;string&gt;;

  constructor(private themeService: ThemeService) {}

  ngOnInit() {
    this.theme$ = this.themeService.theme$;
  } 

}</code></pre>



<p>We can create a provider with the sole purpose of providing the current user’s theme:</p>



<pre class="wp-block-code"><code>export type ActiveThemeProvider = Observable&lt;string&gt;;
export const ACTIVE_THEME = new InjectionToken&lt;ActiveThemeProvider&gt;('Active theme', {
  factory() {
    return inject(ThemeService).theme$;
  }
});</code></pre>



<pre class="wp-block-code"><code>@Component({
  template: `&lt;h1&gt;{{ theme$ | async }}&lt;/h1&gt;`
})
export class HelloComponent {
  constructor(@Inject(ACTIVE_THEME) public theme$: ActiveThemeProvider) {}
}</code></pre>



<p id="03aa">In summary, the benefits of using the <code>InjectionToken</code> factory function are:</p>



<ul>
<li>The provider is tree-shakeable, since we don’t need to inject it in our app module as we’d do with the <code>useFactory</code> provider.</li>
<li>Using <code>inject()</code> to request a provider is faster and more type-safe than providing an additional array of dependencies (which is the common usage of <code>useFactory</code> providers).</li>
<li>The provider has a single responsibility, and our components are injected only with the data they need.</li>
<li>It makes testing more straightforward because we don’t need to mock everything. We can return a mock value from the factory, and that’s all.</li>
</ul>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/angular-injectiontoken-feature/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
