<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Beautiful Angular - Medium]]></title>
        <description><![CDATA[Angular simplifies development and brings joy to web developers worldwide - Medium]]></description>
        <link>https://medium.com/beautiful-angular?source=rss----62a8c32eb39a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Beautiful Angular - Medium</title>
            <link>https://medium.com/beautiful-angular?source=rss----62a8c32eb39a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 16:44:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/beautiful-angular" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Show loader on every request in Angular 2]]></title>
            <link>https://medium.com/beautiful-angular/show-loader-on-every-request-in-angular-2-9a0fca86afef?source=rss----62a8c32eb39a---4</link>
            <guid isPermaLink="false">https://medium.com/p/9a0fca86afef</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angularjs2]]></category>
            <dc:creator><![CDATA[Ivan Radunović]]></dc:creator>
            <pubDate>Sun, 05 Feb 2017 20:12:55 GMT</pubDate>
            <atom:updated>2017-01-24T12:58:43.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpxTNjsS_niaPyIL-bXLFQ.png" /></figure><p>Providing feedback to our users is essential for good user experience. Because Angular is single page application when user navigates to new page browser won’t display usual loading animation.</p><p>Instead user will be presented with empty component and only after data is loaded (from backend) Angular will update views,.. unless you show loading animation from inside Angular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyOR7ok30cN55uEyELg9Vw.gif" /><figcaption>Live Demo GIF</figcaption></figure><p>I know it sounds like simple functionality but I noticed that many developers are asking how to show loader on every http request, so lets start..</p><h3>Custom Http Service</h3><p>First thing needed is custom http service which extends built-in http class.</p><p>In one of my previous posts I wrote about custom http service for JWT authentication, same code is good for this post also. Check that tutorial <a href="https://medium.com/@ivan.radunovic/angular-2-and-jwt-authentication-d30c21a2f24f#.id1n63b9k">here</a>.</p><p>Full project is available on <a href="https://github.com/ivanderbu2/angular-redux">GitHub</a> it includes code from all of my older posts, you can focus your attention on loader part only.</p><pre>get(url: string, options?: RequestOptionsArgs): Observable&lt;any&gt; {</pre><pre>return super.get(this.getFullUrl(url), this.requestOptions(options))<br>            .catch(this.onCatch)<br>            .do((res: Response) =&gt; {<br>                this.onSuccess(res);<br>            }, (error: any) =&gt; {<br>                this.onError(error);<br>            })<br>            .finally(() =&gt; {<br>                this.onEnd();<br>            });</pre><pre>}</pre><p>Code above is showing how I currently handle get requests from custom Http service.</p><p>I have full control over this request so I can call show loader method before call to <strong><em>get</em></strong> method of the super class. I can also call hide loader method from <strong><em>onEnd</em></strong> method, cause at that moment request to the backend will be completed.</p><pre>get(url: string, options?: RequestOptionsArgs): Observable&lt;any&gt; {</pre><pre>    this.showLoader();<br>        <br>    //return super.get ....</pre><pre>}</pre><p>In <strong><em>onEnd</em></strong> method I’ll call <strong><em>hideLoader</em></strong> method:</p><pre>private onEnd(): void {<br>        this.hideLoader();<br>}</pre><p>I still did not create these loader methods in the custom class I’ll construct them as simple logging methods, just temporarily until I create loader service.</p><pre>private showLoader(): void {<br>        console.log(&#39;Show loader&#39;);<br>    }</pre><pre>private hideLoader(): void {<br>        console.log(&#39;Hide loader&#39;);<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*Wuzyt-g6wwqMCZrcxuq7Rw.png" /><figcaption>Console</figcaption></figure><p>Custom service works well</p><h3>Loader</h3><p>Idea is to have loader component which will be included in the main app component and using loader service Angular will trigger visibility state of loader component.</p><h4>Loader component</h4><p>This component holds html and css code for our loader, it will also posses subscription for loader state from Loader Service. Based on the state of loader it will show or hide html code of the loader.</p><pre>import { Component, OnInit, OnDestroy } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { Subscription } from &#39;rxjs/Subscription&#39;;</pre><pre>import { LoaderService } from &#39;./loader.service&#39;;<br>import { LoaderState } from &#39;./loader&#39;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>    selector: &#39;angular-loader&#39;,<br>    templateUrl: &#39;loader.component.html&#39;,<br>    styleUrls: [&#39;loader.component.css&#39;]<br>})<br>export class LoaderComponent implements OnInit {</pre><pre>show = false;</pre><pre>private subscription: Subscription;</pre><pre>constructor(<br>        private loaderService: LoaderService<br>    ) { }</pre><pre>ngOnInit() { <br>        this.subscription = this.loaderService.loaderState<br>            .subscribe((state: LoaderState) =&gt; {<br>                this.show = state.show;<br>            });<br>    }</pre><pre>ngOnDestroy() {<br>        this.subscription.unsubscribe();<br>    }<br>}</pre><h4>Loader component html</h4><p>I am a bit lazy so I will use Angular Material Progress bar component as the loader.</p><pre>&lt;div [class.loader-hidden]=&quot;!show&quot;&gt;<br>    &lt;div class=&quot;loader-overlay&quot;&gt;<br>            &lt;div&gt;<br>                &lt;md-progress-bar mode=&quot;indeterminate&quot; *ngIf=&quot;show&quot;&gt;&lt;/md-progress-bar&gt;<br>            &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Angular Material requires imports in app.module.ts and core.module.ts, I’ll also have to include the theme in index.html file.</p><pre>import { MaterialModule } from &#39;<a href="http://twitter.com/angular/material">@angular/material</a>&#39;;</pre><p>In the app.module.ts imports array item looks like this:</p><pre>MaterialModule.forRoot()</pre><p>And in core.module.ts imports array:</p><pre>MaterialModule</pre><p>I am using Core Module as place where I put services and components required for every action, in this case custom Http Service, Loader Service and Loader Component.</p><p>In index.html I am adding pink theme for Angular Material:</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;<a href="https://unpkg.com/@angular/material/core/theming/prebuilt/pink-bluegrey.css">https://unpkg.com/@angular/material/core/theming/prebuilt/pink-bluegrey.css</a>&quot; type=&quot;text/css&quot;&gt;</pre><h4>Loader service</h4><pre>import { Injectable } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { Subject } from &#39;rxjs/Subject&#39;;</pre><pre>import { LoaderState } from &#39;./loader&#39;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>()</pre><pre>export class LoaderService {</pre><pre>private loaderSubject = new Subject&lt;LoaderState&gt;();</pre><pre>loaderState = this.loaderSubject.asObservable();</pre><pre>constructor() { }</pre><pre>show() {<br>        this.loaderSubject.next(&lt;LoaderState&gt;{show: true});<br>    }</pre><pre>hide() {<br>        this.loaderSubject.next(&lt;LoaderState&gt;{show: false});<br>    }<br>}</pre><p>This service is pretty simple, it posses private property for the subject and public property, observable for that subject.</p><p><strong>LoaderState</strong> is only an interface which holds one boolean property:</p><pre>export interface LoaderState {<br>    show: boolean;<br>}</pre><h4>Loader css</h4><p>I want to display loading progress bar right under address bar in full width, so it will be positioned in absolute manner.</p><pre>.loader-hidden {<br>    visibility: hidden;<br>}<br>.loader-overlay {<br>    position: absolute;<br>    width:100%;<br>    top:0;<br>    left: 0;<br>    opacity: 1;<br>    z-index: 500000;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*JwB9RPyS4DOpOm7X26or8g.png" /><figcaption>Directory structure</figcaption></figure><p>All loader related files are stored in dedicated directory inside the core.</p><h4>Importing loader</h4><p>Because loader is part of the Core Module I will import it there:</p><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [<br>        CommonModule,<br>        MaterialModule<br>    ],<br>    exports: [<br>        LoaderComponent<br>    ],<br>    declarations: [<br>        LoaderComponent<br>    ],<br>    providers: [<br>        LoaderService,<br>        {<br>            provide: HttpService,<br>            useFactory: httpServiceFactory,<br>            deps: [XHRBackend, RequestOptions, LoaderService ]    <br>        }<br>    ]<br>})</pre><pre>export class CoreModule { }</pre><p>And <strong>CoreModule</strong> is imported in imports array of <strong>app.module.ts</strong>.</p><h3>Back to HttpService</h3><p>I need to inject LoaderService through the constructor:</p><pre>constructor(<br>        backend: XHRBackend,<br>        defaultOptions: AngularReduxRequestOptions,<br>        private loaderService: LoaderService<br>    ) { <br>        super(backend, defaultOptions);<br>    }</pre><h4>Show/Hide methods</h4><p>I already called visibility methods from http request, now I’ll update them:</p><pre>private showLoader(): void {<br>        this.loaderService.show();<br>    }</pre><pre>private hideLoader(): void {<br>        this.loaderService.hide();<br>    }</pre><h4>Http service factory</h4><p>Services which extend build-in classes are required to have service provider defined and the factory. I am storing my factories into <strong>_factories</strong> directory. From <strong>CoreModule</strong> decorator you could see how am I defining service provider.</p><p>And this is the factory:</p><pre>import { XHRBackend } from &#39;<a href="http://twitter.com/angular/http">@angular/http</a>&#39;;<br>import { AngularReduxRequestOptions } from &#39;../core/angular-redux-request.options&#39;;<br>import { HttpService } from &#39;../core/http.service&#39;;<br>import { LoaderService } from &#39;../core/loader/loader.service&#39;;</pre><pre>function httpServiceFactory(backend: XHRBackend, options: AngularReduxRequestOptions, loaderService: LoaderService ) {<br>    return new HttpService(backend, options, loaderService);<br>}</pre><pre>export { httpServiceFactory };</pre><p>With this Http service is completed but we will see no loader cause it is not used in the App component.</p><p>Inside <strong>app.component.html</strong> I’ll insert <strong>angular-loader</strong> tag on the first line.</p><h3>Closing</h3><p>Now we have functional loader on every get request, if you are curious to see how it’ll look checkout <a href="https://ivanderbu2.github.io/angular-redux/">Live Demo</a>. Try clicking Load New button few times to see it in action.</p><h4>Source code</h4><p>Entire source code is available on <a href="https://github.com/ivanderbu2/angular-redux">GitHub</a>, feel free to clone, fork and contribute. And please do not open new issues because of that pink loader color, my designer is on vacation ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0fca86afef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beautiful-angular/show-loader-on-every-request-in-angular-2-9a0fca86afef">Show loader on every request in Angular 2</a> was originally published in <a href="https://medium.com/beautiful-angular">Beautiful Angular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 2 and environment variables]]></title>
            <link>https://medium.com/beautiful-angular/angular-2-and-environment-variables-59c57ba643be?source=rss----62a8c32eb39a---4</link>
            <guid isPermaLink="false">https://medium.com/p/59c57ba643be</guid>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ivan Radunović]]></dc:creator>
            <pubDate>Sun, 05 Feb 2017 20:12:41 GMT</pubDate>
            <atom:updated>2017-01-23T17:42:58.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpxTNjsS_niaPyIL-bXLFQ.png" /></figure><p>For all my Angular 2 apps I am using angular-cli, for some time I was developing without it, but when I discovered what options if offers I forgot everything else.</p><p>One of those options is handling different environments. Everyone needs to manage at least 2 environments, one development which uses that localhost:4200 and other for production.</p><h3>Env files</h3><p>In Angular 2 under <strong>src</strong> directory create new one named <strong>environments</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*uzjE-8s0JsQah6PunSWCAQ.png" /></figure><p><strong>environment.ts</strong> is default environment, when you don’t specify — env value that file variables are used.</p><p>Content of default file:</p><pre>export const environment = {<br>  production: false,<br>  apiUrl: &#39;<a href="http://banners.dev/api-angular/&#39;">http://example.com/api/&#39;</a>,<br>};</pre><p>Properties specified here will be available for type hinting throughout entire application.</p><h3>Consuming environment variables</h3><p>In my components, services and other classes when I need some env variable I’ll import default env file, like this:</p><pre>import { environment } from &#39;../../environments/environment&#39;;</pre><p>And now I can use them in my classes as any other object:</p><pre>apiUrl = environment.apiUrl;</pre><p>Angular command line tool knows which file to use for each environment no matter we imported default env file in our classes.</p><h3>Building project</h3><p>Usual way of doing this is with:</p><pre>~prompt$ ng build</pre><p>Without any options above command will use default env file. For production environment:</p><pre>~prompt$ ng build --env=prod</pre><p>This is good now we are built system with production variables, but angular-cli offers one more option:</p><pre>~prompt$ ng build --prod --env=prod</pre><p>This <strong>prod</strong> option will minify all files and do all other sorts of cool things which are not so important right now. It is good to mention that one of my builds went from 7MB to 2.3MB when I used this option.</p><h4>Happy building!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c57ba643be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beautiful-angular/angular-2-and-environment-variables-59c57ba643be">Angular 2 and environment variables</a> was originally published in <a href="https://medium.com/beautiful-angular">Beautiful Angular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 2 and JWT authentication]]></title>
            <link>https://medium.com/beautiful-angular/angular-2-and-jwt-authentication-d30c21a2f24f?source=rss----62a8c32eb39a---4</link>
            <guid isPermaLink="false">https://medium.com/p/d30c21a2f24f</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Ivan Radunović]]></dc:creator>
            <pubDate>Sun, 05 Feb 2017 20:12:26 GMT</pubDate>
            <atom:updated>2017-01-23T17:34:40.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpxTNjsS_niaPyIL-bXLFQ.png" /></figure><p>You can pass Authorization headers in couple of ways, solution I presented here is a bit more elaborate cause it could include loading spinner and centralized error handling for each http request.</p><h3>Extending Http service</h3><p>First thing to do is to create custom Http service cause we need to pass some headers in each request.</p><pre>import { Injectable } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre>import {<br>    Http,<br>    RequestOptions,<br>    RequestOptionsArgs,<br>    Response,<br>    Request,<br>    Headers,<br>    XHRBackend<br>} from &#39;<a href="http://twitter.com/angular/http">@angular/http</a>&#39;;</pre><pre>import { Observable } from &#39;rxjs/Observable&#39;;<br>import &#39;rxjs/Rx&#39;;</pre><pre>import { MyCustomRequestOptions } from &#39;../_helpers/request-options&#39;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a> ()</pre><pre>export class HttpService extends Http {</pre><pre>public token: string;</pre><pre>apiUrl = &#39;http://example.com/api/&#39;;</pre><pre>constructor(<br>        backend: XHRBackend,<br>        defaultOptions: MyCustomRequestOptions<br>        ) {<br>            super(backend, defaultOptions);<br>        }</pre><p>From the code above everything is pretty clear, only new thing is <strong>MyCustomRequestOptions</strong> class which is injected into constructor.</p><h3>Appending headers</h3><p>Usual way of doing JWT authentication is by passing Authorization header with the actual token. There are other ways like passing the token via query parameter but then we wouldn’t need headers.</p><p>To be able to pass custom headers to http service we need to extend <strong>BaseRequestOptions</strong> class.</p><pre>import { BaseRequestOptions } from &#39;<a href="http://twitter.com/angular/http">@angular/http</a>&#39;;</pre><pre>export class MyCustomRequestOptions extends BaseRequestOptions {</pre><pre>public token: string;</pre><pre>constructor (customOptions?: any) {</pre><pre>super();<br>        let user = JSON.parse(localStorage.getItem(&#39;user&#39;));<br>        this.token = user &amp;&amp; user.token;<br>        this.headers.append(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>        this.headers.append(&#39;Authorization&#39;, &#39;Bearer &#39; + this.token );        <br>        <br>    }<br>}</pre><p>From constructor you can see that I am calling superclass constructor first and after that I am extracting value of token from local storage.</p><p>You can get that value however you want in my case I stored <strong>user</strong> object in local storage and it posses JWT token.</p><h3>Back to custom Http service</h3><p>Now I need to overwrite each http method that I am going to use, that is the place to display some spinner to the user and do error handling.</p><pre>// HttpService</pre><pre>get(url: string, options?: RequestOptionsArgs): Observable&lt;any&gt; {</pre><pre>return super.get(this.getFullUrl(url), this.requestOptions(options))<br>            .catch() // Catch exception here<br>            .do((res: Response) =&gt; {<br>                // Handle success, maybe display notification<br>            }, (error: any) =&gt; {<br>                // Handle errors<br>            })<br>            .finally(() =&gt; {<br>                // Request completed<br>            });<br>    }</pre><pre>private getFullUrl(url: string): string {<br>        return this.apiUrl + url;<br>    }</pre><pre>private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {</pre><pre>if (options == null) {<br>            options = new MyCustomRequestOptions();<br>        }</pre><pre>if (options.headers == null) {<br>            options.headers = new Headers();<br>        }</pre><pre>return options;<br>    }</pre><p>For this example I took <strong><em>get</em></strong> method, I am also using few helper methods for full url and request options.</p><p>I will import this service into <strong>CoreModule</strong>, cause it extends built-in class it needs to have service provider defined and factory:</p><pre>import { NgModule } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { CommonModule } from &#39;<a href="http://twitter.com/angular/common">@angular/common</a>&#39;;<br>import { XHRBackend, RequestOptions } from &#39;<a href="http://twitter.com/angular/http">@angular/http</a>&#39;;</pre><pre>import { HttpService } from &#39;./http.service&#39;;<br>import { httpServiceFactory } from &#39;../_factories/http-service.factory&#39;;<br>import { AngularReduxRequestOptions } from &#39;./angular-redux-request.options&#39;;</pre><pre><a href="http://twitter.com/NgModule">@NgModule</a>({<br>    imports: [<br>        CommonModule<br>    ],<br>    exports: [<br>    ],<br>    declarations: [<br>    ],<br>    providers: [<br>        {<br>            provide: HttpService,<br>            useFactory: httpServiceFactory,<br>            deps: [XHRBackend, RequestOptions]    <br>        }<br>    ]<br>})</pre><pre>export class CoreModule { }</pre><h4>Factory</h4><p>I am storing my factories inside <strong>_factories</strong> directory:</p><pre>import { XHRBackend } from &#39;<a href="http://twitter.com/angular/http">@angular/http</a>&#39;;<br>import { AngularReduxRequestOptions } from &#39;../core/angular-redux-request.options&#39;;<br>import { HttpService } from &#39;../core/http.service&#39;;</pre><pre>function httpServiceFactory(backend: XHRBackend, options: AngularReduxRequestOptions) {<br>    return new HttpService(backend, options);<br>}</pre><pre>export { httpServiceFactory };</pre><h3>Closing</h3><p>The only thing left now is importing <strong>CoreModule</strong> into <strong>AppModule</strong>.</p><h4>Source code</h4><p>Entire source code is published on <a href="https://github.com/ivanderbu2/angular-redux">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d30c21a2f24f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beautiful-angular/angular-2-and-jwt-authentication-d30c21a2f24f">Angular 2 and JWT authentication</a> was originally published in <a href="https://medium.com/beautiful-angular">Beautiful Angular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 2 and Redux simplified]]></title>
            <link>https://medium.com/beautiful-angular/angular-2-with-redux-using-ngrx-store-2f93a8ad0dd?source=rss----62a8c32eb39a---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f93a8ad0dd</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[store]]></category>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[Ivan Radunović]]></dc:creator>
            <pubDate>Sun, 05 Feb 2017 20:10:11 GMT</pubDate>
            <atom:updated>2017-01-22T19:28:47.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpxTNjsS_niaPyIL-bXLFQ.png" /></figure><p>Live demo and code available.</p><h3>Redux: Buzzword for simple idea</h3><p>Redux sounds like some new cool technology but in fact it is more of a convention in how our frontend apps consume data.</p><p>Main idea is to store every piece of data in centralized container and change it only using set of predefined actions (something like dispatching an event). This way data flows in only one direction and chances of breaking something are reduced.</p><h3>Why Redux in Angular project?</h3><p>I started using this approach while I was developing one huge HTML5 banner creation software and ad serving network. There were so many components and services inside that Angular project and bits of data were scattered all over the place.</p><p>I knew there has to be some better way to store data and soon I discovered <a href="https://github.com/ngrx/store">ngrx/store</a> project. From their GitHub repository:</p><blockquote>RxJS powered state management for Angular applications, inspired by Redux</blockquote><p>They also offer many free tools, I mostly use their DevTools for Google Chrome. It shows current state of store as well as detailed timeline of dispatched actions and store modifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*i88ws34vDdUrTMhVzI1GSg.png" /><figcaption>Redux DevTools</figcaption></figure><p>From above image you can see how easy it is to look for certain changes or store variables, much easier than any other way of handling data in Angular.</p><h3>Installation</h3><p>I am using angular-cli for my projects and thanks to it I don’t have to think about SystemJS and loading 3rd party packages.</p><pre>npm install @ngrx/core @ngrx/store --save</pre><p>For DevTools package:</p><pre>npm install @ngrx/store-devtools --save</pre><p>I will import <strong>ngrx</strong> module into <strong>app.module.ts</strong> component and DevTools module:</p><pre>import { StoreDevtoolsModule } from &#39;<a href="http://twitter.com/ngrx/store-devtools">@ngrx/store-devtools</a>&#39;;</pre><pre>import { StoreModule } from &#39;<a href="http://twitter.com/ngrx/store">@ngrx/store</a>&#39;;</pre><p>In imports array I’ll import these 2 modules:</p><pre>imports: [<br>    //...<br>    StoreModule.provideStore({ <br>      //place for future reducers<br>    }),<br>    StoreDevtoolsModule.instrumentOnlyWithExtension()<br>  ],</pre><p>Everything is clear from above steps, only new term is <strong>reducer</strong>.</p><h3>Reducers</h3><p>In terms of ngrx/store package, reducers are list of possible actions (in this case pure functions) for each property defined in the store. I am coming from PHP/Laravel background, so most similar to reducers are Event Listeners or Command Handlers.</p><p>Usual actions for each resource are CREATE, UPDATE and DELETE.</p><p>This is one of my reducers:</p><pre>export const campaigns = (state: any = [], {type, payload}) =&gt; {<br>    switch (type) {<br>        case &#39;ADD_CAMPAIGNS&#39;:<br>            return payload;<br>        case &#39;CREATE_CAMPAIGN&#39;: <br>            return [...state, payload];<br>        case &#39;UPDATE_CAMPAIGN&#39;:<br>            return state.map(campaign =&gt; {<br>                return campaign.token === payload.token ? Object.assign({}, campaign, payload): campaign;<br>            });<br>        case &#39;DELETE_CAMPAIGN&#39;: <br>            return state.filter(campaign =&gt; {<br>                return campaign.token !== payload.token;<br>            });<br>        default: <br>            return state;<br>    }<br>}</pre><p>I am storing my reducers in dedicated directory <strong>_reducers</strong> and this reducer above is named <strong>campaign.reducer.ts</strong>.</p><p>Angular needs to be aware of this new reducer so I’ll include it in app module:</p><pre>import { campaigns } from &#39;./_reducers/campaign.reducer&#39;;</pre><p>I will push this new reducer into StoreModule:</p><pre>imports: [<br>    //...<br>    StoreModule.provideStore({ <br>      campaigns<br>    }),<br>    StoreDevtoolsModule.instrumentOnlyWithExtension()<br>  ],</pre><h3>App Store</h3><p>Reducers are way of changing data in the store, but we still need some way to read that data.</p><p>That is done using application store, centralized place where all of store properties are kept. In terms of TypeScript that is a simple interface with dedicated properties for each store and type of each property is actual model which is used.</p><p>I am storing app.store.ts file in root folder of my application, on same level as app.module.ts</p><pre>import { Campaign } from &#39;./_models/campaign&#39;;</pre><pre>export interface AppStore {<br>    campaigns: Campaign[];<br>    // other properties...<br>}</pre><h3>Service for manipulating AppStore</h3><p>I created simple convention for my Angular projects, it says:</p><blockquote>Angular services communicate with AppStore in both ways. They dispatch actions and they read data from the store.</blockquote><p>This way components only need to inject service instance and when something changes it is usually easily changed on only one place, the service.</p><pre>import { Injectable } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { Response, Http } from &#39;<a href="http://twitter.com/angular/http">@angular/http</a>&#39;;<br>import { Observable } from &#39;rxjs/Observable&#39;;<br>import { Store } from &#39;<a href="http://twitter.com/ngrx/store">@ngrx/store</a>&#39;;</pre><pre>import { Campaign } from &#39;../_models/campaign&#39;;</pre><pre>import { BaseService } from &#39;../_services/base.service&#39;;<br>import { HttpService } from &#39;../core/http.service&#39;;</pre><pre>import { AppStore } from &#39;../app.store&#39;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>()</pre><pre>export class CampaignService extends BaseService {</pre><pre>    // Redux based variables<br>    campaigns: Observable&lt;Array&lt;Campaign&gt;&gt;; </pre><pre>constructor(<br>        private http: HttpService,<br>        private store: Store&lt;AppStore&gt;<br>        ) {<br>            super();<br>            this.campaigns = store.select( store =&gt; store.campaigns);<br>        }</pre><pre>//...</pre><p>Focus your attention on the constructor of <strong>CampaignService</strong> class. You can see I am using DI to create <strong>AppStore</strong> instance, and in the definition of the constructor I am selecting campaign store and assigning it’s value to <strong><em>campaigns</em></strong> property.</p><p>Store returns observable, so we can subscribe in our components and listen for changes, which is a big plus.</p><h4>Using the service</h4><p>I will skip import part of the component and class definition, I’ll just show most important parts of <strong>CampaignComponent</strong> here:</p><pre>// Redux based variables<br>campaigns: Observable&lt;Array&lt;Campaign&gt;&gt;;</pre><pre>private subscription: Subscription;</pre><pre>constructor(<br>        private campaignService: CampaignService<br>        ) { <br>            this.campaigns = campaignService.campaigns;<br>        }</pre><pre>ngOnInit() {<br>        this.subscription = this.campaigns<br>                    .subscribe(<br>                        campaigns =&gt; {<br>                            //Do something<br>                        }<br>                            ,<br>                        error =&gt; <br>                            //Do something<br>                    );</pre><pre>        this.campaignService.loadCampaigns();<br>     }</pre><pre>ngOnDestroy() {<br>        this.subscription.unsubscribe();<br>    }</pre><p>In the constructor of this component I am injecting CampaignService instance, after that I am creating link between CampaignService property <strong><em>campaigns</em></strong> and components property <strong><em>campaigns</em></strong>.</p><p>This allows me to directly use campaigns in component, I can print them using <strong>async</strong> pipe or I subscribe for changes as I did in this example.</p><p>In ngOnDestroy method I am removing subscription, this is important for preventing memory leaks, I won’t go into details, it is good to accept this practice as convention.</p><h3>Loading data via REST</h3><p>You may noticed call to loadCampaigns method in CampaignComponent, that method is actually contacting backend and loading data into Redux store.</p><p>Cause I am using observables when new data is loaded in the store, my components will immediately be updated with new content.</p><pre>loadCampaigns()  {<br>        return this.http.get(this.campaignUrl)<br>                        .map((res: Response) =&gt; {<br>                            let body = res.json();<br>                            return body.data || {};<br>                        })<br>                        .map((payload: Campaign[] ) =&gt; {<br>                            return { type: &#39;ADD_CAMPAIGNS&#39;, payload };<br>                        })<br>                        .subscribe((action) =&gt; {<br>                            this.store.dispatch(action);<br>                        });<br>    }</pre><p>In loadCampaigns I am using custom http class which extends <strong><em>angular/http </em></strong>class. That way I can pass authentication headers into every request and manage error/status handling on one place. I described my custom http service <a href="https://medium.com/@ivan.radunovic/angular-2-and-jwt-authentication-d30c21a2f24f#.dge3324pv">here</a>.</p><p>Cause authentication is different topic let’s imagine that <strong>http </strong>is angular class and that this route is unprotected.</p><p>First map statement accepts backend response, encodes it in JSON and passes <strong>data</strong> property if it exists or empty object if not.</p><p>Second map statement takes content of data property and creates array of Campaign objects. After that it returns simple object with defined action type and payload.</p><p>Finally subscribe statement takes passed action and dispatches it to Redux reducer.</p><p>That’s all.</p><h3>Redux in Angular equals simplicity</h3><p>At first it may look like overkill, defining reducer for each resource, inserting that reducer into StoreModule, adding new property into AppStore, injecting AppStore into service, … returning observables from the store, but when you get used to it, it starts to make sense.</p><p>Let us imagine simple <strong>app.component.html</strong> file which only prints list of campaigns:</p><pre>&lt;ul&gt;<br>    &lt;li *ngFor=&quot;let campaign of (campaigns | async)&quot;&gt;<br>       {{campaign.name}}<br>    &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>As soon as <strong><em>loadCampaigns</em></strong> method returns response, this list will be updated. And not only that list, any other service/component which uses same store will be updated.</p><h4>Lazy loaded modules</h4><p>When you create lazy loaded module or complicated routing module with many levels of lazy loaded modules it becomes too complicated to track which instance of service is used in which module.</p><p>This same campaignService without Redux could return different data in 2 modules, because it’s using new instance.</p><p>With centralized store you don’t care is it same service instance or not, cause store is always the same and service is only accessing data inside the store.</p><blockquote>I don’t recommend intentionally creating many instances of same service (service should be singleton) but sometimes you just can’t complete the task without it.</blockquote><h3>Live Demo and Source code</h3><p>I’ve been asked about code for this tutorial so I created <a href="https://github.com/ivanderbu2/angular-redux">GitHub repository</a> with entire code and few extras.</p><p>I also created <a href="https://ivanderbu2.github.io/angular-redux/">Live demo</a> and deployed it on GitHub Pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYXevLOvKm796tRSVujKCA.png" /><figcaption>Live Demo Screenshot</figcaption></figure><p>I didn’t remove DevTools module from the deploy, so you will be able to track store changes if you install <a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en">DevTools Crhome extension</a>.</p><h3>Closing</h3><p>I am pretty new to Angular 2, I guess it couldn’t be different :) and many concepts were new to me. What I liked about it is TypeScript and strong conventions introduced.</p><p>On small projects these conventions are too much, but for any larger project they are welcomed.</p><p>I would like to hear how you complete similar tasks in your own projects, do you use Redux? What about requests to backend?</p><h3>Valuable feedbacks</h3><p><a href="https://medium.com/u/9ce5a72c3b92">Renato Perez</a> brought my attention to wrong terms used in Reducers section and pointed me to <a href="https://github.com/ngrx/effects">ngrx/effects</a> project for more elegant data loading.</p><blockquote>I think good feedbacks are like shortcuts to better code and thank you for that.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f93a8ad0dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beautiful-angular/angular-2-with-redux-using-ngrx-store-2f93a8ad0dd">Angular 2 and Redux simplified</a> was originally published in <a href="https://medium.com/beautiful-angular">Beautiful Angular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>