<?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[alexonozor - Medium]]></title>
        <description><![CDATA[In-depth articles about Angular by a core front-end JavaScript developer and African web Evangelist. - Medium]]></description>
        <link>https://medium.com/alexonozor?source=rss----8a5401108520---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>alexonozor - Medium</title>
            <link>https://medium.com/alexonozor?source=rss----8a5401108520---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:01:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/alexonozor" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Angular Interceptor: Adding Headers and Handling Token Expiry]]></title>
            <link>https://medium.com/alexonozor/angular-interceptor-adding-headers-and-handling-token-expiry-b66dd4eade07?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/b66dd4eade07</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 04:46:51 GMT</pubDate>
            <atom:updated>2023-11-22T02:39:06.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*L_43ik1_Rz_9ZwUQUfi94w.png" /></figure><p>Angular interceptors are a powerful tool that enables developers to manipulate HTTP requests and responses globally. In this article, we’ll explore how to use Angular interceptors to add headers to outgoing requests and handle scenarios where a token has expired, redirecting the user to the login page.</p><h3>Setting Up the Angular Project</h3><p>Let’s start by creating a new Angular project using the Angular CLI. Open your terminal and run the following commands:</p><pre>ng new angular-interceptor-demo<br>cd angular-interceptor-demo</pre><h3>Creating an Interceptor for Headers</h3><p>We’ll first create an interceptor that adds a custom header to each outgoing HTTP request. Create a new file named header-interceptor.ts: code</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import {<br>  HttpRequest,<br>  HttpHandler,<br>  HttpEvent,<br>  HttpInterceptor,<br>} from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Injectable()<br>export class HeaderInterceptor implements HttpInterceptor {<br>  intercept(<br>    request: HttpRequest&lt;any&gt;,<br>    next: HttpHandler<br>  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    const modifiedRequest = request.clone({<br>      setHeaders: {<br>        &#39;X-Custom-Header&#39;: &#39;Custom Header Value&#39;,<br>      },<br>    });</pre><pre>    return next.handle(modifiedRequest);<br>  }<br>}</pre><p>This interceptor uses the clone method to create a modified request with an additional custom header.</p><h3>Creating an Interceptor for Token Expiry</h3><p>Now, let’s create an interceptor to check for token expiry and redirect the user to the login page if necessary. Create a new file named token-interceptor.ts:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import {<br>  HttpRequest,<br>  HttpHandler,<br>  HttpEvent,<br>  HttpInterceptor,<br>} from &#39;@angular/common/http&#39;;<br>import { Observable, throwError } from &#39;rxjs&#39;;<br>import { catchError } from &#39;rxjs/operators&#39;;<br>import { Router } from &#39;@angular/router&#39;;</pre><pre>@Injectable()<br>export class TokenInterceptor implements HttpInterceptor {<br>  constructor(private router: Router) {}</pre><pre>  intercept(<br>    request: HttpRequest&lt;any&gt;,<br>    next: HttpHandler<br>  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    return next.handle(request).pipe(<br>      catchError((error) =&gt; {<br>        if (error.status === 401) {<br>          // Token expired, redirect to login page<br>          this.router.navigate([&#39;/login&#39;]);<br>        }<br>        return throwError(error);<br>      })<br>    );<br>  }<br>}</pre><p>In this interceptor, we use the catchError operator to intercept HTTP errors. If the error status is 401 (Unauthorized), we assume the token has expired and redirect the user to the login page using the Angular Router.</p><h3>Registering the Interceptors</h3><p>Now, let’s register these interceptors in the Angular module. Open the app.module.ts file:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { HttpClientModule, HTTP_INTERCEPTORS } from &#39;@angular/common/http&#39;;<br>import { RouterModule } from &#39;@angular/router&#39;;</pre><pre>import { AppComponent } from &#39;./app.component&#39;;<br>import { HeaderInterceptor } from &#39;./header-interceptor&#39;;<br>import { TokenInterceptor } from &#39;./token-interceptor&#39;;</pre><pre>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [<br>    BrowserModule,<br>    HttpClientModule,<br>    RouterModule.forRoot([]), // Add your routes here<br>  ],<br>  providers: [<br>    {<br>      provide: HTTP_INTERCEPTORS,<br>      useClass: HeaderInterceptor,<br>      multi: true,<br>    },<br>    {<br>      provide: HTTP_INTERCEPTORS,<br>      useClass: TokenInterceptor,<br>      multi: true,<br>    },<br>  ],<br>  bootstrap: [AppComponent],<br>})<br>export class AppModule {}</pre><p>In the providers array, we provide instances of both HeaderInterceptor and TokenInterceptor. The multi: true option allows multiple interceptors.</p><h3>Testing the Interceptors</h3><p>You can now test the interceptors in your components. For example, make an HTTP request in your component:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;button (click)=&quot;makeRequest()&quot;&gt;Make Request&lt;/button&gt;<br>  `,<br>})<br>export class AppComponent {<br>  constructor(private http: HttpClient) {}</pre><pre>  makeRequest() {<br>    this.http.get(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;).subscribe(<br>      (data) =&gt; {<br>        console.log(&#39;Response:&#39;, data);<br>      },<br>      (error) =&gt; {<br>        console.error(&#39;Error:&#39;, error);<br>      }<br>    );<br>  }<br>}</pre><p>Ensure you have defined routes in your application, including a route for the login page, so that the token interceptor can redirect the user when needed.</p><h3>Conclusion</h3><p>Angular interceptors are a valuable feature for handling HTTP requests and responses in a centralized and reusable manner. By creating interceptors for adding headers and handling token expiry, you can enhance the security and functionality of your Angular applications. These interceptors provide a clean and modular way to manage cross-cutting concerns in your HTTP communication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b66dd4eade07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/angular-interceptor-adding-headers-and-handling-token-expiry-b66dd4eade07">Angular Interceptor: Adding Headers and Handling Token Expiry</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Material Design Icon in NativeScript]]></title>
            <link>https://medium.com/alexonozor/using-material-design-icon-in-nativescript-53ae0835d447?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/53ae0835d447</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[nativescript-angular]]></category>
            <category><![CDATA[nativescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-material]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Fri, 12 Aug 2022 21:22:38 GMT</pubDate>
            <atom:updated>2022-08-12T21:25:51.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*jLgWOUyAcEM9_tVkp4Ge_w.png" /></figure><p>Integrating icons in Nativescript at first was a little intimidating and confusing, we have a lot of bugs and questions with people struggling to get it right, a lot of plugins have been created for this purpose but have since not been maintained which raised a lot of issues around icons again but thanks to the Nativescript team, especially with this earlier versions you can simply using any icon as a font by creating a font folder at the root of your application and then referencing it in your stylesheet.</p><p>I wrote an article about using font-awesome with Nativescript around last year but several questions have been asked about using Angular material Icons with NS and it’s basically the same process. let me demonstrate it here in pictural means.</p><p><strong>Step 1 — Download fonts.<br></strong>- Navigate to the angular material icons repo on GitHub: <a href="https://github.com/google/material-design-icons">https://github.com/google/material-design-icons</a><br>- Click on font and download the variants of your choices notice I download the regular and the outline fonts below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*Fi7Drmf_KtyKs390KFFUhA.png" /><figcaption>Select the font folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMtLzA5mm38OGeFT3yQaSA.png" /><figcaption>Download the checked variant</figcaption></figure><p>Steps 2</p><p>Copy the download font into your fonts folder in your nativescript application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*cMF9gKAT1Uz6w4w4zVCudQ.png" /></figure><p>You are good to go the last thing is to reference the fonts you need in your app.css or app.scss. See how I separated the <strong>regular</strong> from the <strong>outline</strong> varient.</p><p><em>./app.scss</em></p><p>.m-icon { <em>// or any other class name you prefer</em></p><p>font-family: “Material Icons”, “MaterialIcons-Regular”;</p><p>font-weight: 400;</p><p>}</p><p>.m-icon-outline { <em>// or any other class name you prefer</em></p><p>font-family: “Material Icons”, “MaterialIconsOutlined-Regular”;</p><p>font-weight: 400;</p><p>}</p><p>In my template (.html) I can easily use an icon with the icon code and separate the variant with the class i.e <strong>Regular</strong> or <strong>outline</strong> with the class name:</p><p><strong>Regular Home Icon<br></strong>&lt;Label text=”&amp;#xe88a;” class=”<strong>m-icon</strong>&quot;&gt;&lt;/Label&gt;</p><p><strong>Outline Icon<br></strong>&lt;Label text=”&amp;#x<strong>e88a</strong>;” class=”<strong>m-icon-outline</strong>&quot;&gt;&lt;/Label&gt;</p><p>If you ever wonder how I got the icon code kindly navigate to the material <a href="https://fonts.google.com/icons?selected=Material+Icons&amp;icon.style=Outlined">icon page</a>, click on an Icon you will get the code, copy and paste it after the <strong>&amp;#xe+code</strong> and you will smile when you look at your simulator or emulator :)</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53ae0835d447" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/using-material-design-icon-in-nativescript-53ae0835d447">Using Material Design Icon in NativeScript</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Disabling Form Controls When Working With Reactive Forms in Angular]]></title>
            <link>https://medium.com/alexonozor/disabling-form-controls-when-working-with-reactive-forms-in-angular-fd651524e?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/fd651524e</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular-reactive-form]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Sat, 22 Jan 2022 04:15:40 GMT</pubDate>
            <atom:updated>2022-01-11T11:45:42.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IifxmVNdWVXhy0yErO3ckA.png" /></figure><p>When working with Angular <strong>Reactive Forms</strong> there are times when you need to disable/enable a form control, for example:</p><p>&lt;input [formControl]=”formControl” [disable]=”condition”&gt;</p><p>If you’ve ever tried the above code, you probably have encountered the following warning.</p><p><em>It looks like you’re using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. </em><strong><em>We recommend using this approach to avoid ‘changed after checked’ errors.</em></strong></p><p>Angular tells you that it’s better for you to use the ways it gives you to disable/enable form controls.</p><p>You can enable/disable a form control by using the following ways:</p><ol><li>Instantiate a new FormControl with the disabled property set to true. FormControl({value: &#39;&#39;, disabled: true}) .</li><li>Calling control.disable() or control.enable() .</li></ol><p>But sometimes you miss(😳) or need the method you’re used to (👆). Let’s create a directive that will help us recreate this functionality.</p><pre>import { NgControl } from &#39;@angular/forms&#39;;<br><br>@Directive({<br>  selector<strong>: </strong>&#39;[disableControl]&#39;<br>})<br>export class DisableControlDirective {<br><br>  @Input() set disableControl( condition <strong>: </strong>boolean ) {<br>    const action <strong>= </strong>condition <strong>? </strong>&#39;disable&#39; <strong>: </strong>&#39;enable&#39;;<br>    this.ngControl.control[action]();<br>  }<br><br>  constructor( private ngControl <strong>: </strong>NgControl ) {<br>  }<br><br>}</pre><p>We can get a reference to the form control instance via DI. Then it is only a matter of calling the correct method according to the Input() value.</p><p>Now we can use our directive like this:</p><p>&lt;input [formControl]=”formControl” <strong>[disableControl]=”disable”</strong>&gt;<br>&lt;button (click)=”disable = true”&gt;Disable&lt;/button&gt;<br>&lt;button (click)=”disable = false”&gt;Enable&lt;/button&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*hM9JOtAY_YsMZ6Ng-TGJpg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd651524e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/disabling-form-controls-when-working-with-reactive-forms-in-angular-fd651524e">Disabling Form Controls When Working With Reactive Forms in Angular</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s New in Angular 9?]]></title>
            <link>https://medium.com/alexonozor/whats-new-in-angular-9-d6a0ea1e0aa4?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/d6a0ea1e0aa4</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 19:05:11 GMT</pubDate>
            <atom:updated>2019-12-09T19:05:11.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*2zzlaw_zNjYhXCMtlNhY9A.png" /></figure><p><strong>Angular 9</strong> is the smaller, faster, and easier to use and it will be making Angular developers life easier. The full version of <a href="https://www.code-sample.com/2019/08/whats-new-in-angular-9-angular-9-new.html"><strong>Angular 9</strong></a> will be released in the month of <strong><em>October/November 2019</em></strong>.</p><p>Explore this: <a href="https://www.code-sample.com/2019/10/angular-9-vs-angular-8-vs-angular-7-vs.html"><em>Angular 9 vs. Angular 8 vs. Angular 7 vs. Angular 6, 5, 4, 2</em></a></p><p><strong>Added Angular 9 Features</strong> -</p><p>1. Added undecorated classes migration schematic in the core.</p><p>2. The formControlName also accepts a number in the form</p><p>3. Now allow selector-less directives as base classes in View Engine in the compiler.</p><p>4. Added support selector-less directive as base classes in Ivy and also make the Ivy compiler the default for ngc.</p><p>5. Convert all ngtsc diagnostics to ts. Diagnostics</p><p>6. bazel: support ts_library targets as entry-points for ng_package.</p><p>7. core: add dynamic queries schematic.</p><p>8. core: Mark TestBed.get as deprecated.</p><p>9. ivy: expose window.ng.getDebugNode helper and also support ng-add in localize package.</p><p>10. ivy: i18n — add syntax support for $localize metadata block.</p><p>11. ivy: i18n — reorganize entry-points for better reuse.</p><p>12. language-service: enable logging on TypeScriptHost.</p><p>13. language-service: provide diagnostic for invalid templateUrls.</p><p>14. language-service: provide diagnostics for invalid styleUrls.</p><p><strong>DEPRECATIONS -</strong></p><p>core: TestBed.get function is marked as deprecated, use TestBed.inject instead.</p><p><strong>Performance Improvements :</strong></p><ol><li>Binding update benchmark and also convert all node-based benchmark to use a testing harness.</li><li>Avoid megamorphic reads during property binding.</li><li>Avoid repeated lview reads in pipe instructions.</li><li>Avoid repeated LView reads in property instructions.</li><li>Avoid unnecessary DOM reads in styling instructions.</li><li>Initialise TNode inputs/outputs on the first creation pass for the Ivy.</li><li>limit TNode.outputs reads for the ivy.</li></ol><p>8. The language-service, keep analyzedModules cache when source files don’t change.</p><pre>It looks like -<br>describe(‘TypeScriptServiceHost’, () =&gt; {<br> it(‘should not clear caches when external template changes’, () =&gt; {<br> const tsLSHost = new MockTypescriptHost([‘/app/main.ts’], toh);<br> const tsLS = ts.createLanguageService(tsLSHost);<br> const ngLSHost = new TypeScriptServiceHost(tsLSHost, tsLS);<br> const oldModules = ngLSHost.getAnalyzedModules();<br> tsLSHost.override(‘/app/test.ng’, ‘&lt;div&gt;&lt;/div&gt;’);<br> const newModules = ngLSHost.getAnalyzedModules();<br> expect(newModules).toBe(oldModules);<br> });</pre><pre>});</pre><p><strong>Angular 9 Breaking Changes</strong> -</p><p><strong>1) Ivy applications :-</strong></p><p>Previously, in Ivy applications, Hammer providers were included by default. With this commit, apps that want Hammer support must import <a href="https://www.code-sample.com/2019/08/whats-new-in-angular-9-angular-9-new.html"><strong>HammerModule</strong> </a>in their root module i.e.</p><p>import {HAMMER_PROVIDERS} from ‘./dom/events/hammer_gestures’</p><p><strong>2) ServiceWorker: </strong><br>Remove deprecated option versionedFiles from service worker asset group configuration in ngsw-config.json</p><p><strong>Before</strong></p><pre>“assetGroups”: [<br> {<br> “name”: “test”,<br> “resources”: {<br> “versionedFiles”: [<br> “/**/*.txt”<br> ]<br> }<br> }<br>]</pre><p><strong>After</strong></p><pre>“assetGroups”: [<br> {<br> “name”: “test”,<br> “resources”: {<br> “files”: [<br> “/**/*.txt”<br> ]<br> }<br> }<br>]</pre><p><strong>Angular 9 Bug Fixes</strong> -</p><p><strong>common</strong>: update $locationShim to notify onChange listeners before emitting AngularJS events.</p><p><strong>compiler</strong>: return enableIvy true when using readConfiguration</p><p><strong>ivy</strong> -</p><p>1. Get name directly from nativeNode</p><p>2. Handle empty bindings in template type checker</p><p>3. In ngcc, handle inline exports in commonjs code</p><p>4. The ngcc should only index .d.ts exports within the package</p><p>5. The ngTemplateOutlet error when switching between null and template value</p><p><strong>language-service</strong> -</p><p>1. Instantiate MetadataResolver once</p><p>2. Remove ‘context’ used for module resolution</p><p><strong>ngcc</strong> -</p><p>1. Handle deep imports that already have an extension</p><p>2. Ignore format properties that exist but are undefined</p><p><strong>Reference link</strong> — <a href="https://github.com/angular/angular/blob/master/CHANGELOG.md"><em>https://github.com/angular/angular/blob/master/CHANGELOG.md</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*Zxvnxuq3GEsxs9eH.jpg" /></figure><p><strong>Compatibility note</strong>: The primary goal of the backward compatibility promise is to ensure that changes in the core framework and tooling don’t break the existing ecosystem of components and applications and don’t put undue upgrade/migration burden on Angular application and component authors.</p><p><strong>Note</strong>: Angular versions ^4.0.0 and ^5.0.0 are no longer under support.</p><p>Enjoy!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6a0ea1e0aa4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/whats-new-in-angular-9-d6a0ea1e0aa4">What’s New in Angular 9?</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shit happens, deal with it!]]></title>
            <link>https://medium.com/alexonozor/shit-happens-deal-with-it-ea381343abe6?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/ea381343abe6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Wed, 15 May 2019 19:31:50 GMT</pubDate>
            <atom:updated>2019-05-15T19:31:50.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*lbAU3lkcFY9vwIPLMBqrnA@2x.jpeg" /></figure><h3>Error Handling in Angular</h3><p>When shit happens, Other folks tell you to “Have hope, there is light at the end of the tunnel; even if you can’t see it.” Today you have stubble upon various solutions in dealing with the most important part of the error handling shit in Angular.</p><p>Though when it happens you can choose to ignore it and let it bring shame, that’s not my prayers for you, I know it’s complicated but the best way to tackle them depends on where they come from:</p><h4><strong>External Errors</strong></h4><p>Are the easiest ones; why (is that) you can always blame someone else like the backend guys or administrator because it is not directly your fault but In this cases, we can’t do much more than handle them, notify the user and pray to the administrator to repair it.</p><p>This errors usually come from the server and its properties have a <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_errors">status</a> code starting with 5 (5xx…) and an explanation message, so we are able to know what caused it and react properly. Though, they are some that we can’t handle, like a browser or an OS crash.</p><h4><strong>Internal Errors</strong></h4><p>It is all your fault, you need to accept that you have failed to fix this kind of errors and learn the lesson.</p><p>What runs through your mind now is how you can differentiate them right? but the good news is that they will notify you when they come.</p><p><strong><em>The Server: </em></strong><em><br></em>Seems that the properties in the server’s errors are not fixed, at least I haven’t found any standard.</p><p>A server error might contain:<br>- <strong>status</strong> (or code): Code status starting with 4 (4xx…). <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors">There are 28 status</a>.<br>- <strong>name</strong>: The name of the error (ie: HttpErrorResponse).<br>- <strong>message</strong>: Explanation message (ie: Http failure response for…).</p><p><strong><em>The Client </em></strong>(browser): <br>Based on a generic Error constructor, Javascript throws an Error each time something goes wrong. Most common errors are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a> (call to a non-existent variable) and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError">TypeError</a> (ie: try to execute a variable, as it was a function). There are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">5 more types.</a></p><p>A client error should contain:<br><strong>- name</strong> (ie: ReferenceError).<br><strong>- message</strong> (ie: X is not defined).<br>And in most modern browsers: <strong>fileName, lineNumber </strong>and<strong> columnNumber </strong>where<strong> </strong>the error happened<strong>,</strong> and <strong>stack </strong>(last X functions called before the error)<strong>.</strong></p><h4>Errors, Exceptions &amp; CallStack</h4><p>When Error happens, an exception is thrown at the current point of execution which removes every <strong>callstack</strong> until the exception is handled by a <strong><em>try/catch</em></strong><em> </em>block. If the error exceptions are not handled, this will cause the flow of the application stack to break and you will embarrass yourself in front of your users. Damn shit!</p><h3>How to deal with all this shit</h3><p>By default, Angular comes with its own <a href="https://angular.io/api/core/ErrorHandler"><strong>ErrorHandler</strong></a><strong> </strong>that intercepts all the Errors but if we use that we just want life to control us, let’s control life. Create a new class in your life called: <strong>ErrorsHandler</strong></p><pre><em>// errors-handler.ts</em><br>import { ErrorHandler, Injectable} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>()<br>export class <strong>ErrorsHandler</strong> implements <strong>ErrorHandler</strong> {</pre><pre><strong>handleError</strong>(<strong>error</strong>: Error) {<br>     // Do whatever you like with the error (send it to the server?)<br>     // And log it to the console<br>     <strong>console.error</strong>(&#39;It happens: &#39;, error);<br>  }<br>}</pre><p>Don’t be too rude with Angular before it curses you with errors that will confuse you, just tell Angular you have a class you want to use instead of its default, trust me, Angular is your God here it will allow you. (Provide it)</p><pre><em>// errors.module.ts<br></em><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports: [ ... ],<br>  declarations: [ ... ],<br>  <strong>providers: [<br>    {<br>      provide: ErrorHandler,<br>      useClass: ErrorsHandler,<br>    }<br>  ]</strong><br>}</pre><p>Now, every time a new shit (error) happens, Angular will log ‘It happens’ followed by the error itself in the console.</p><h3>How to recognize them</h3><p>Inside the ErrorHandler, we can check which kind of error it is:</p><pre><em>// errors-handler.ts</em><br>import { ErrorHandler, Injectable} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import { HttpErrorResponse } from &#39;@angular/common/http&#39;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>()<br>export class <strong>ErrorsHandler</strong> implements <strong>ErrorHandler</strong> {</pre><pre><strong>handleError</strong>(<strong>error</strong>: Error | HttpErrorResponse) {<strong>   </strong><br>   if (error instanceof HttpErrorResponse) {<br>      <strong>// Server or connection error happened</strong><br>      if (!navigator.onLine) {<br>        <strong>// Handle offline error</strong><br>      } else {<br>        <strong>// Handle Http Error </strong>(error.status === 403, 404...)<strong><br></strong>      }<br>   } else {<br>     <strong>// Handle Client Error </strong>(Angular Error, ReferenceError...)     <br>   }</pre><pre><strong>// Log the error anyway</strong><br>  console.error(&#39;It happens: &#39;, error);<br>}</pre><h3>How to react to each one</h3><h4>Server and connection errors</h4><p>Server and connection errors<strong> </strong>affect in the way the app communicates with the server. If the app is not online, the resource doesn’t exist (404), the user is not allowed to access the data (403)… HttpClient will give us an informative Error that we have to handle, but our app won’t crash and the risk of data corruption or lost can be managed.</p><p>As a general rule, I think this kind of errors need a notification; a clear message explaining to the user what is happening and how to proceed.</p><p>For this purpose, we’ll use a <strong>notification service.</strong></p><pre><em>// errors-handler.ts</em><a href="http://twitter.com/Injectable"><br>@Injectable</a>()<br>export class ErrorsHandler implements ErrorHandler {</pre><pre>constructor(<br>       <strong><em>// Because the ErrorHandler is created before the providers, we’ll have to use the Injector to get them.</em></strong><em><br></em>       <strong>private injector: Injector</strong>,<br>   ) { }</pre><pre>handleError(<strong>error</strong>: Error | HttpErrorResponse) {<br>  <br>   <strong>const notificationService = this.injector.get(NotificationService);</strong></pre><pre>if (error instanceof HttpErrorResponse) {<br>      // Server or connection error happened<br>      if (!navigator.onLine) {<br>        // Handle offline error<br>        <strong>return notificationService.notify(&#39;No Internet Connection&#39;);</strong><br>      } else {<br>        // Handle Http Error (error.status === 403, 404...)<br>        <strong>return notificationService.notify(`${error.status} - ${error.message}`);</strong><br>      }<br>   } else {<br>     // Handle Client Error (Angular Error, ReferenceError...)     <br>   }</pre><pre><strong>// Log the error anyway</strong><br>  console.error(&#39;It happens: &#39;, error);<br>}</pre><p><em>* Here we could handle specific errors. For example, if it is a 403 error, we could notify the user and then redirect to the login page.</em></p><p>Because the best Error is the one that never happens, we could improve our error handling using an <strong>HttpInterceptor </strong>that would intercept all the server calls and retry them X times before throwing an Error:</p><pre><em>// server-errors.interceptor.ts</em><br>import { Injectable } from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import {<br>  HttpRequest,<br>  HttpHandler,<br>  HttpEvent,<br>  HttpInterceptor,<br>  HttpErrorResponse<br>} from &#39;<a href="http://twitter.com/angular/common">@angular/common</a>/http&#39;;</pre><pre>import { Observable } from &#39;rxjs/Observable&#39;;<br>import &#39;rxjs/add/operator/retry&#39;;</pre><pre><a href="http://twitter.com/Injectable">@Injectable</a>()<br>export class ServerErrorsInterceptor implements <strong>HttpInterceptor</strong> {<br>  <br>  <strong>intercept</strong>(<strong>request</strong>: HttpRequest&lt;any&gt;, <strong>next</strong>: HttpHandler):     Observable&lt;HttpEvent&lt;any&gt;&gt; {<br>    // If the call fails, retry until 5 times before throwing an error<br>    <strong>return next.handle(request).retry(5);</strong><br>  }<br>}</pre><p>Then we’ll need to tell Angular that he should use our ServerErrorsInterceptor class in every HTTP call:</p><pre><em>// errors.module.ts<br></em><a href="http://twitter.com/NgModule">@NgModule</a>({<br>  imports: [ ... ],<br>  declarations: [ ... ],<br>  <strong>providers: [<br>    </strong>{<br>      <strong>provide: HTTP_INTERCEPTORS,<br>      useClass: ServerErrorsInterceptor,<br>      multi: true,</strong><br>    },<br>  <strong>]</strong><br>})</pre><h4>Client errors</h4><p>Client errors seem more dangerous to me. They could completely crash our app, originate corrupt data that could be stored in the server, keep the user working on stuff that wouldn’t be saved…</p><p>I think that this situation claims for a more strict response: If something is broken in our app, we need to stop the app, redirect the user to an error screen with all the information, fix it asap and inform to the user that it has been fixed.</p><p>For that we could use an ErrorComponent that takes the Error details from the route’s query params:</p><pre><em>// errors-handler.ts<br></em><a href="http://twitter.com/Injectable">@Injectable</a>()<br>export class ErrorsHandler implements ErrorHandler {</pre><pre>constructor(<br>   private injector: Injector<br>) { }</pre><pre>handleError(<strong>error</strong>: Error | HttpErrorResponse) {<br>  <br>   const notificationService = this.injector.get(NotificationService);<br>   <strong>const router = this.injector.get(Router);</strong></pre><pre>if (error instanceof HttpErrorResponse) {<br>      // Server or connection error happened<br>      if (!navigator.onLine) {<br>        // Handle offline error<br>        return notificationService.notify(&#39;No Internet Connection&#39;);<br>      } else {<br>        // Handle Http Error (error.status === 403, 404...)<br>        return notificationService.notify(`${error.status} - ${error.message}`);<br>      }<br>   } <strong>else {<br>     // Handle Client Error (Angular Error, ReferenceError...)<br>     router.navigate([&#39;/error&#39;], { queryParams: {error: error} });<br>   }</strong></pre><pre><strong>// Log the error anyway</strong><br>  console.error(&#39;It happens: &#39;, error);<br>}</pre><h3>How to keep track of the errors</h3><p>This is the best way of stopping rubbish in life but African men used to say: “Elders don’t rush talk” let’s keep this discussion till next week stay tuned for Part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea381343abe6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/shit-happens-deal-with-it-ea381343abe6">Shit happens, deal with it!</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FontAwesome 5 and NativeScript 4.2 Angular]]]></title>
            <link>https://medium.com/alexonozor/fontawesome-5-and-nativescript-4-2-angular-ca29826f9346?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/ca29826f9346</guid>
            <category><![CDATA[nativescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[font-awesome]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Wed, 17 Oct 2018 23:04:20 GMT</pubDate>
            <atom:updated>2018-10-17T23:06:27.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>FontAwesome 5 and NativeScript 4.2 [Angular]</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eq9DeI2FGe8b16a3acLICg.jpeg" /></figure><p>FontAwesome is an awesome library for adding icons to a web, mobile, and desktop applications. hay!! it now in version 5, with a whole lot of beautiful icons that may fit the need of your application. So I thought I could also use it with NativeScript 4.2(latest) + Angular 6, although it turned out to be a bit different than I expected.</p><p>There are a lot of articles and tutorials that show how to use FontAwesome and NativeScript but since the release of FontAwsome 5 and NativeScript 4.2 + Angular things have really changed from both ends and none of those old methods will work if you are using this new stable version.</p><h4>How to use FontAwesome 5 with NativeScript 4.2 + Angular</h4><p>First, we need to download FontAwesome from their website. <a href="https://fontawesome.com/">Go to the site</a>, navigate to <a href="https://fontawesome.com/how-to-use/on-the-web/setup/getting-started?using=web-fonts-with-css"><strong>how to use</strong></a><strong> </strong>then scroll to the <strong>host it yourself section, </strong>click download FontAwesome for free, you can choose to pay for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4c4BUhshJN0kw8b93Y_qg.png" /></figure><p>After downloading, here is where things become tricky from your NativeScript-Angular, The new NTS-ng file structure has changed since the release of 4.2. the app directory has been moved to the /<strong>src</strong> directory as you would expect in every angular-cli 2+ project. So let’s create a <strong>/fonts</strong> folder inside the <strong>/src </strong>directory like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hixsHOcuGQU2tyOQn8rkXg.png" /></figure><p>Then, open the zip file and go to <strong>fontawesome-free/web-fonts-with-css/webfonts </strong>and we will copy/move every <strong>.ttf</strong> file into the <strong>src/fonts</strong> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*geQdM3zG8SUM1GaDYrPDvA.gif" /></figure><p>Now we can add the fonts to our <strong>app.css</strong> like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08128b38686ed1e3795ace7f716a2e87/href">https://medium.com/media/08128b38686ed1e3795ace7f716a2e87/href</a></iframe><p>That’s it, now we can use FontAwesome 5 in our app. To do that first, we have to find an icon. Go to the icon search page and then pick an icon. You need this two things:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqe0g0-FeMlO8uitHIApSg.png" /></figure><p>The first one will be the class (fas) and the other one will be the code (f015).</p><p>Now we can insert the icon in our app template like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b68416f6ff86c30af9a1319d76d38dc8/href">https://medium.com/media/b68416f6ff86c30af9a1319d76d38dc8/href</a></iframe><p>And that’s it! Now we can use FontAwesome 5 icons in our NativeScript 4.2 Angular app without using third-party plugins!</p><p>Thanks for your time reading and do not forget to clap if you like it so others can benefit.</p><p><a href="https://medium.com/@alexonozor?source=post_header_lockup">Alex Onozor</a><br>Frontend(web &amp; mobile), JavaScriptor(Lover of Angular ≤=&gt; Angular Lover), Web evangelist. Open source contributor. Software Architect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca29826f9346" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/fontawesome-5-and-nativescript-4-2-angular-ca29826f9346">FontAwesome 5 and NativeScript 4.2 Angular]</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular compiler under the microscope (Part 1)]]></title>
            <link>https://medium.com/alexonozor/angular-compiler-under-the-microscope-part-1-e977601437e0?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/e977601437e0</guid>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[angular-4]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Wed, 29 Nov 2017 21:27:46 GMT</pubDate>
            <atom:updated>2017-11-29T21:27:46.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Q1bieMZKeXiP49kXTqE5w.jpeg" /></figure><p>If you agree with me Angular compiler is worth taken to the lab. Recently, I wanted to know what is going on behind the Angular compilation process so it was time to dismantle and see for myself. Honestly it was very interesting and thanks to the great minds (<a href="https://angular.io/about?group=Angular">Google Angular developers team</a>) for building such a wonderful engine.</p><p>As with many of my posts, I think it’s a good idea to follow along as I go, and therefore there are few things you’ll need to have installed on your machine before we get started if you’d like to follow along.</p><p><em>I won’t be talking about the installation process of this packages since it’s almost out side of the scope.</em></p><h3>Packages Needed in this Lab</h3><ol><li><a href="https://nodejs.org/en/download/">Node js</a> &amp; (NPM or Yarn).</li><li><a href="https://cli.angular.io/">Angular CLI</a></li></ol><p>We also need another great tools<em> source-map-explorer</em></p><pre>npm i -g source-map-explorer</pre><h3>Getting started</h3><p>Alright, now it’s time to pick up your microscope and let see what the compiler got, to begin lets create a new project to play with, go to your work directory and type:</p><pre>ng new compiler-microscope</pre><p>This will take a minute but you will end up with a new project and don’t forget to change directory into the project and type:</p><pre>ng build</pre><p>This will create a dist folder with the compiled application. You’ll notice that the size of the result JavaScript files is quite big, if you look inside of the dist folder, you will see a<strong> <em>vendor.bundle.js</em></strong><em> </em>file which is about 2 mb in size this is obviously not ideal!</p><p>Pick up your microscope and take a look inside the <strong><em>vendor.bundle.js</em></strong> file you’ll see tons of JavaScript, none of this is minified. We can minify them with a package called uglify to get — about 650kb but this is still very big for a plain hello word application.</p><p>This is where source-map-explorer comes into play — it allows as to peak into the bundle and find out what makes it big, lets try by typing:</p><pre>source-map-explorer dist/vendor.bundle.js</pre><p>Wait a few seconds and get an out put that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*8E1afSFVU01rE5lyjK8MuA.png" /></figure><p>We can see that the compiler module accounts for nearly 50% of the bundle that is about 1mb (or 320kb when minified). Luckily it’s very easy to get rid of that compiler simply <em>run</em></p><pre>ng build -prod --sourcemaps</pre><p>to remove the compiler part. This is what the AOT (Ahead of time) compilation is doing under the wood.</p><p>Now, have a look at the dist directory: the vendor javascript file has now shrunk to 310kb and using source-map-explorer we can see that the big compiler chunks now gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*8E1afSFVU01rE5lyjK8MuA.png" /></figure><p>We can also shave off another 30% of the bundle size by removing the forms and the HTTP modules(if we don’t need them) — hoping in the future the build system will be smart enough to do this for us. Terms for removing unusual code is called “Tree shaking”. Then, if we actually remove forms and HTTP the fill will fall to just around 79kb.</p><p>So what is angular compiler doing here? How come we have removed it and the app still works? why is it needed in the first place? All this questions will be answered in the next article(Part 2) because looking at the microscope for too long can affect your eyes so lets take a break :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e977601437e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/angular-compiler-under-the-microscope-part-1-e977601437e0">Angular compiler under the microscope (Part 1)</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular rxjs: Please Always Unsubscribe()]]></title>
            <link>https://medium.com/alexonozor/angular-rxjs-please-always-unsubscribe-86ca55ba7f12?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/86ca55ba7f12</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[angular-4]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Thu, 28 Sep 2017 13:31:10 GMT</pubDate>
            <atom:updated>2017-09-28T14:52:21.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*l6JH9rraQP6buictmRDpRg.jpeg" /></figure><p>One of the finest library Angular 2.x+ featured is rxjs i.e reactive programming which kicks of it’s duty as soon as you subscribe() to it.</p><p>In this article, we will learn how to unsubscribe from an observable stream following this three points.</p><ol><li>Why you need to unsubscribe.</li><li>When you should unsubscribe.</li><li>How you unsubscribe.</li></ol><h3><strong>Why you need to unsubscribe.</strong></h3><p><a href="http://reactivex.io/rxjs/">Reactive-Extensions for JavaScript</a> (or RxJS) introduces the concept of Observables to Angular. If you have been used to version 1 of Angular then you are likely comfortable with Promises. And, while you might think an Observable is just like a Promise you might be surprised (as I was) to learn that they are in fact very different.</p><p>First, Promises are eager and are executed immediately. Observables are not eager and are only executed when subscribed to.</p><p>Second, Promises are asynchronous. Observables can be either synchronous or asynchronous.</p><p>Third, Promises are expected to return only a single value (like a function). Observables can return zero, one or more (infinitely) values.</p><p>Let me get to the point. A subscription is created when we subscribe() to an observable. And it is important that we unsubscribe from any subscriptions that we create in our Angular components to avoid memory leaks.</p><h3>When you likely should unsubscribe</h3><p><em>when</em> do we unsubscribe? In most instances the best time to unsubscribe is when your component is destroyed. Angular introduced the the ngOnDestroy() <a href="https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html">lifecycle method</a>:</p><blockquote>ngOnDestroy(): Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.</blockquote><h4>AsyncPipe</h4><p>Before we go any farther; if you are using observable streams via the AsyncPipe then you do not need to worry about unsubscribing. The async pipe will take care of subscribing and unsubscribing for you.</p><h3>How you unsubscribe.</h3><p>You can unsubscribe anytime from observable stream anytime by using the unsubscribe() method.</p><p>The unsubscribe methods simply store the subscription and invoke the <a href="http://reactivex.io/rxjs/class/es6/Subscription.js~Subscription.html#instance-method-unsubscribe">unsubscribe()</a> method when the component is destroyed.</p><h4>unsubscribe()</h4><p>First, let’s assume we have a UserService class with an authenticate() method:</p><pre>@Injectable()<br>export class UserService {</pre><pre>  public authenticate(email: string, password: string): Observable&lt;User&gt; {<br>    //code omitted<br>  }<br>}</pre><p>In our component we first import the OnDestroy class from <em>@angular/core</em> as well as the ISubscription interface from rxjs:</p><pre>import { OnDestroy } from &quot;@angular/core&quot;;<br>import { ISubscription } from &quot;rxjs/Subscription&quot;;</pre><p>Next, we implement the abstract class and declare a variable to store a reference to our subscription:</p><pre>export class MyComponent implements OnDestroy {</pre><pre>  private subscription: ISubscription;</pre><pre>}</pre><p>Next, let’s subscribe to the observable returned from the UserService.authenticate() method. In this example I have a method that is invoked when a login form is submitted:</p><pre>public onSubmit() {<br>  //authenticate the user via the UserService<br>  this.subscription = this.userService.authenticate(email, password).subscribe(user =&gt; {<br>    this.user = user;<br>  });<br>}</pre><p>Finally, when our component is destroyed we unsubscribe:</p><pre>ngOnDestroy() {<br>  this.subscription.unsubscribe();<br>}</pre><p>If we are subscribing to multiple subscriptions we do not need to use a collection to store all of the subscription instances. Rather, a subscription can have <em>child</em> subscriptions. Simply invoke the add()method to add additional child subscriptions. This is helpful, as all child subscriptions will be unsubscibed when we unsubscribe() the parent subscription.</p><p>Let’s add an additional subscription:</p><pre>getUser(id: string) {<br>  const subscription = this.userService.get(id)<br>    .subscribe(user =&gt; {<br>      this.user = user;<br>    });<br>  this.subscription.add(subscription);<br>}</pre><p>In the code above we are getting an additional user by their id value from the REST API, and we are subscribing to the observable that is returned from the get() method. We simply add() this new subscription to our existing subscription object. Then, invoke the unsubscribe() method, just like we did before:</p><pre>ngOnDestroy() {<br>  this.subscription.unsubscribe();<br>}</pre><p>Now, both the primary subscription (to the authenticate() method) is unsubscribed, as well as the child subscription (to the get() method).</p><h3>Which method?</h3><p>The question you might be asking yourself at this point is:</p><blockquote>Which method should I use to unsubscribe?</blockquote><p>First, I would recommend that you use the async pipe. It makes sense to abstract this away and to let the Angular framework handle the subscriptions for you.</p><p>If using the async pipe is not a good solution for your needs, then I would recommend you to use the unsubscribe() method as shown above, whichever is more convenient for you and your application.</p><p>Thanks for your time, don’t forget to keep clapping and please don’t unsubscribe() form my articles :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86ca55ba7f12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/angular-rxjs-please-always-unsubscribe-86ca55ba7f12">Angular rxjs: Please Always Unsubscribe()</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Reactive Forms]]></title>
            <link>https://medium.com/alexonozor/angular-reactive-forms-c66f9e9201a?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/c66f9e9201a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angular-4]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Sat, 02 Sep 2017 09:39:18 GMT</pubDate>
            <atom:updated>2017-09-02T09:39:17.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*2VYnENYSQQ2VV2XO3ZsXVg.jpeg" /></figure><p>Data driven applications uses form as one of their biggest data input source. <strong>Two-ways-data-binding</strong> frameworks/libraries like Angular is doing pretty well because of it <em>ng-model, which </em>made creating dynamic forms easy.</p><p>Angular 2.X+ offers two form-building technologies: <strong><em>reactive</em> forms</strong> and <strong><em>template-driven</em> forms</strong>. The two technologies belong to the @angular/forms library and share a common set of form control classes but they diverge markedly in philosophy, programming style, and technique. They even have their own modules: the <a href="https://angular.io/api/forms/ReactiveFormsModule">ReactiveFormsModule</a> and the <a href="https://angular.io/api/forms/FormsModule">FormsModule</a>.</p><p>In this article, we want to focus on <strong><em>Reactive From.</em></strong></p><p>For demonstration, we are going to be building a simple <strong>user registration </strong>application but let’s use this time to talk about <strong>Reactive form.</strong></p><h3>Reactive Form</h3><p>Angular <em>reactive</em> forms facilitate a <em>reactive style</em> of programming to get data in and out of the <strong>form</strong> from where it is been defined in the component to the template visa versa through the use of <strong>Form Model and Form Directives</strong>. Reactive forms offer the ease of using reactive patterns, testing, and validation.</p><h4>Form Model</h4><p>The form model is a UI-independent representation of a form. It consists of three building blocks<strong>: <em>FormControl</em>, <em>FormGroup</em>, and <em>FormArray</em>.</strong></p><h4>Form Directives</h4><p><strong>These are the directives connecting the form model to the DOM</strong> (e.g., <em>NgModel</em>). <em>FormsModule</em> and <em>ReactiveFormsModule</em> provide different sets of these directives. Let’s set them up!</p><h3>Setup</h3><p>A good place to start is the <strong>UI-independent(Form Model) so </strong>Let’s assume we are in our users Component class taking the <strong>FormControl</strong>.</p><h4><strong>Form Control</strong></h4><p>FormControl is a directive that allows you to create and manage a FormControl instance directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67a3781f6c02fec57dae0f5cef70e6fd/href">https://medium.com/media/67a3781f6c02fec57dae0f5cef70e6fd/href</a></iframe><p>The above code shows a formControl called userName. this will be available in our template. A FormControl constructor accepts three, optional arguments: <em>the initial data value, an array of validators, and an array of async validators</em>. Notice our simple control doesn’t have a validator, lets bind it to our template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4dd8d62c65f4b624f0df8e435414339/href">https://medium.com/media/a4dd8d62c65f4b624f0df8e435414339/href</a></iframe><h4><strong>Form Group</strong></h4><p>The above setup isn’t bad for a single FormControl, but what if we have multiple controls we want to bind in our template. it means we need to group them together with <strong><em>FormGroup</em></strong><em> </em>which also allow nested grouping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a9ac70671c59a7f3f2b8bf72a4b598a/href">https://medium.com/media/7a9ac70671c59a7f3f2b8bf72a4b598a/href</a></iframe><p>Now that you’ve made changes in the class, they need to be reflected in the template. Update user.component.html by replacing it with the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/258ba40d846cd03306bfd8c5d8cc7929/href">https://medium.com/media/258ba40d846cd03306bfd8c5d8cc7929/href</a></iframe><p>formGroup is a reactive form directive that takes an existing FormGroup instance and associates it with an HTML element. In this case, it associates the FormGroup you saved as userForm with the form element.</p><p>With a parent FormGroup, the userName input needs the syntaxformControlName=&quot;userName&quot; in order to be associated with the correct FormControl in the class. This syntax tells Angular to look for the parent FormGroup, in this case userForm and then, <em>inside</em> that group to look for a FormControl called userName.</p><p>Let’s test to see if the value really works add the following line of code to see.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6b9374744254ce28094784f85484939/href">https://medium.com/media/f6b9374744254ce28094784f85484939/href</a></iframe><p>The userForm.value returns the <em>form model</em>. Piping it through the <a href="https://angular.io/api/common/JsonPipe">JsonPipe</a> renders the model as JSON in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*G7UBJkXnljaMZhaXX6Lbew.png" /></figure><p>The initial userName property value is the empty string. Type into the <em>name</em> input box and watch the keystokes appear in the JSON.</p><p>Great! You have the basics of a form.</p><h4><strong>Nested FormGroups</strong></h4><p>Right now the user’s form only have userName and we need to add more fields to it like first name, last name, and address. Address will contain some fields like: street, city, Zip code. This means that our address needs to be nested, here is how our form group will look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6b9374744254ce28094784f85484939/href">https://medium.com/media/f6b9374744254ce28094784f85484939/href</a></iframe><p>We will bind the nested filed to the form in the template below. notice the new attribute called <strong><em>formGroupName</em></strong> have the address as a value, this directive instruct the form about where the nested group starts from in our case is address.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b529812cac8d1d48edb725cb63fa4828/href">https://medium.com/media/b529812cac8d1d48edb725cb63fa4828/href</a></iframe><p>After these changes, the JSON output in the browser shows the revised <em>form model</em> with the nested address <a href="https://angular.io/api/forms/FormGroup">FormGroup</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Io2xayzf_izcMEUoDsZ6bQ.png" /></figure><p><strong>The status of a group is calculated as follows:</strong></p><ul><li>If one of its children is invalid, the group is invalid.</li><li>If all of its children are valid, but the group itself has errors, the group is invalid.</li><li>If all of its children are valid, and the group has no errors, the group is valid.</li></ul><p>At the moment, you’re dumping the entire form model onto the page. Sometimes you’re interested only in the state of one particular FormControl which we can achieve with the .get() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c41968effda09dc0df3ed31d781d9b64/href">https://medium.com/media/c41968effda09dc0df3ed31d781d9b64/href</a></iframe><p>formControl has other handy method to check validity too.</p><h3>Reactive form validation</h3><p>Right now our form looks good and well nested, but what if we want to add validation to it? Well, the reactive form has a Hugh support for validations(Buit-in), it also gave us the ability to write a custom validation.</p><p>To start using reactive form validation, we need to import the Validation and import it into the user’s component.</p><p>`import { FormGroup, Validators } from ‘@angular/forms’;`</p><h4>Built-in validators</h4><p>Angular has three major built-in validators which are checks for presence (Validators.required) and length (Validators.maxLength, Validators.minLength). You can also support multiple validations using array, Let’s make use of them in our user Form.</p><p>We’ll validates the presence of userName and the minimum length should be 4 characters. here is the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f2a1c2b831bfdd199f275e8f9e7fe6/href">https://medium.com/media/e8f2a1c2b831bfdd199f275e8f9e7fe6/href</a></iframe><p>What if we want to validate the style character of our username not to have some certain character? we need to write our own custom validation for it, Angular gives us the ability to do this.</p><h4>Custom validations.</h4><p>Since the built-in validators won’t always match the exact use case of your application, sometimes you’ll want to create a custom validator. Here is what a simple custom validation function looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9acbab141f1eb8dae770624c8083929c/href">https://medium.com/media/9acbab141f1eb8dae770624c8083929c/href</a></iframe><p>The forbiddenNameValidator factory returns the configured validator function. That function takes an Angular control object and returns <em>either</em> null if the control value is valid <em>or</em> a validation error object. The validation error object typically has a property whose name is the validation key, &#39;forbiddenName&#39;, and whose value is an arbitrary dictionary of values that you could insert into an error message, { userName }.</p><h4>Adding to reactive forms</h4><p>In reactive forms, custom validators are fairly simple to add. All you have to do is pass the function directly to the <a href="https://angular.io/api/forms/FormControl">FormControl</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bdcd97bdf88a16929f3a35675965ef0/href">https://medium.com/media/5bdcd97bdf88a16929f3a35675965ef0/href</a></iframe><h4>There are two types of validator functions: sync validators and async validators.</h4><ul><li><strong>Sync validators:</strong> functions that take a control instance and immediately return either a set of validation errors or null. You can pass these in as the second argument when you instantiate a FormControl.</li><li><strong>Async validators:</strong> functions that take a control instance and return a Promise or Observable that later emits a set of validation errors or null. You can pass these in as the third argument when you instantiate a FormControl.</li></ul><h3>Populate the form model with setValue and patchValue</h3><p>Previously you created a control and initialized its value at the same time. You can also initialize or reset the values <em>later</em> with the setValue and patchValue methods.</p><h4>setValue</h4><p>With setValue, you assign <em>every</em> form control value <em>at once</em> by passing in a data object whose properties exactly match the <em>form model</em> behind the <a href="https://angular.io/api/forms/FormGroup">FormGroup</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d13876ad5530c52942269a371360b399/href">https://medium.com/media/d13876ad5530c52942269a371360b399/href</a></iframe><p>The setValue method checks the data object thoroughly before assigning any form control values.</p><p>It will not accept a data object that doesn’t match the FormGroup structure or is missing values for any control in the group. This way, it can return helpful error messages if you have a typo or if you’ve nested controls incorrectly. patchValue will fail silently.</p><p>On the other hand,setValue will catch the error and report it clearly.</p><p>Notice that you can <em>almost</em> use the entire user as the argument to setValue because its shape is similar to the component&#39;s <a href="https://angular.io/api/forms/FormGroup">FormGroup</a> structure.</p><h4>patchValue</h4><p>With patchValue, you can assign values to specific controls in a FormGroup by supplying an object of key/value pairs for just the controls of interest.</p><p>This example sets only the form’s userName control.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f946775f5ecae937d0b55bbf5d76b39a/href">https://medium.com/media/f946775f5ecae937d0b55bbf5d76b39a/href</a></iframe><p>With patchValue you have more flexibility to cope with wildly divergent data and form models. But unlike setValue, patchValue cannot check for missing control values and does not throw helpful errors.</p><h3>Reset the form flags</h3><p>You can at any time rest the form to it initial states by using the .reset() method. you can also rest it to a stage by passing a params to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc50a1af738078d7f8aaacf0b1e110d0/href">https://medium.com/media/bc50a1af738078d7f8aaacf0b1e110d0/href</a></iframe><h3>Wrapping Up</h3><p>This article covered:</p><ul><li>How to create a reactive form component and its corresponding template.</li><li>Grouping FormControls.</li><li>inbuilt-validation &amp; Custom validation</li><li>Inspecting <a href="https://angular.io/api/forms/FormControl">FormControl</a> properties.</li><li>Setting data with patchValue and setValue.</li><li>Resting FormControls</li></ul><p>It has been a long day for us reacting with Angular Reactive Forms :) . I will also recommend you to checkout out the this <a href="https://angular.io/generated/live-examples/reactive-forms/final.eplnkr.html">sample application </a>built by the the Angular team, also do me a favor of reading the documentation about reactive forms.</p><p>See you next week….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c66f9e9201a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/angular-reactive-forms-c66f9e9201a">Angular Reactive Forms</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preloading Angular  Modules with: Alex Onozor]]></title>
            <link>https://medium.com/alexonozor/preloading-modules-angular-2-c6b2625d6e22?source=rss----8a5401108520---4</link>
            <guid isPermaLink="false">https://medium.com/p/c6b2625d6e22</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angular-4]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[route-optimization]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[Alex Onozor]]></dc:creator>
            <pubDate>Tue, 29 Aug 2017 06:30:19 GMT</pubDate>
            <atom:updated>2017-08-29T06:30:19.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preloading Modules — Angular Router</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*uS37lvBi7Fa1nSDRy6mxuw.jpeg" /><figcaption>Preloading modules</figcaption></figure><p>Last week was all about <a href="https://medium.com/alexonozor/lazy-loading-angular-module-routing-9e29bab91821">lazy-loading</a>, were we learnt how to split our application into feature modules and load them on demand. The issue with lazy-loading is that when the user navigates to the lazy-loadable section of the application, the router will have to fetch the required modules from the server, which will take time.</p><p>We can fix this issue by adding preloading to our route, of which the route can load our lazy-loaded modules asynchronously while the user is interacting with other parts of the application, this makes it more faster when the user visit any preloaded module as this will fetch from a cache.</p><p>In this article, I will continue from our E-Commerce styled application, adding preloading to the lazy-loaded functionality from where we left it.</p><p><a href="https://medium.com/alexonozor/lazy-loading-angular-module-routing-9e29bab91821">In the last article</a> we have a file called <strong><em>main.route.ts</em></strong> where our initial route is setup. which uses the<em> </em><strong>app.module.ts</strong>.</p><p>Notice: The <strong>HomeComponent</strong> is eager loaded and angular will render it after the application has finished boostraping .</p><pre>import { Routes } from &#39;@angular/router&#39;;</pre><pre>// HomeComponent this components will be eager loaded<br>import { HomeComponent } from &#39;./home/home.component&#39;;<br>  <br>export const routes: Routes = [   <br>   { path: &#39;&#39;, component: HomeComponent, pathMatch: &#39;full&#39; },<br>   <strong>{ path: &#39;shop&#39;, loadChildren: &#39;./shop/shop.module#ShopModule&#39; },</strong><br>   { path: &#39;**&#39;, component: HomeComponent }<br> ]</pre><p>When angular is done rending our HomeComponent, the user is ready to start interacting with other features modules of the application. We can do our user so well by preloading some of this modules in the background with some simple configuration.</p><h4>Enabling Preloading</h4><p>To enable preloading we need to pass a preloading strategy into forRoot.</p><pre>@NgModule({ <br> bootstrap: [HomeComponent],  <br> imports: [RouterModule.forRoot(routes, { preloadingStrategy:      PreloadAllModules })]<br>})</pre><p>And the preloadingStrategy came from the <em>‘@angular/router’</em> so you will need to import it.</p><pre>import { PreloadAllModules } from <a href="https://angular.io/api/router">‘@angular/router’</a>;</pre><h4>Custom Preloading Strategy</h4><p>The latest version of the router ships are in two strategies: <strong>preload nothing </strong>and <strong>preload all modules</strong>, but you can provide your own. And it is actually a lot simpler that it may seem. For instance, start loading the rest of the modules in 5s after app is loaded:</p><pre><strong>export</strong> <strong>class</strong> CustomPreloadingStrategy <strong>implements</strong> PreloadingStrategy{</pre><pre>preload(route: Route, fn: () =&gt; Observable&lt;boolean&gt;):        Observable&lt;boolean&gt; {<br> <strong>return</strong> Observable.of(<strong>true</strong>).delay(5000).flatMap( (_:boolean)=&gt;fn());<br> }<br>}</pre><p>We can explicitly setup a preloader by telling angular which module we want to preload with this simple configuration <em>data: {preload: true}</em>.</p><pre>export const routes: Routes = [   <br>   { path: &#39;&#39;, component: HomeComponent, pathMatch: &#39;full&#39; },<br>   <strong>{ path: &#39;shop&#39;, loadChildren: &#39;./shop/shop.module#ShopModule&#39;,<br>     data: {preload: true} },</strong><br>   { path: &#39;**&#39;, component: HomeComponent }<br> ]</pre><p>having a preloadStratagies class let’s call it PreloadSelectedModules.</p><pre>export class PreloadSelectedModules implements PreloadingStrategy { <br> preload(route: Route, load: Function): Observable&lt;any&gt; {<br>    return route.data &amp;&amp; route.data.preload ? load() : of(null);<br>  }<br>}</pre><p>The preload method takes two parameters: a <strong>route</strong> and the <strong>function</strong> that actually does the preloading. In it, we can check if the preload property is set to true. And if it is, we call the load function.</p><p>Alright!!! as you can see, the angular routing architecture is very huge, flexible, and fantastic. I know they’re a lot of things we can still do with it. next week we’ll be doing something a bit more advance; we will be talking about how Angular <strong>detect’s changes</strong> and what makes it awesome. stay tune! subscribe and don’t forget to drop your comments then share.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b2625d6e22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/alexonozor/preloading-modules-angular-2-c6b2625d6e22">Preloading Angular  Modules with: Alex Onozor</a> was originally published in <a href="https://medium.com/alexonozor">alexonozor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>