<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jonathan Casarrubias on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Casarrubias on Medium]]></description>
        <link>https://medium.com/@jcasarrubias?source=rss-4298d94ff69b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pwccuCH8QJgMM94WfwNoZQ.png</url>
            <title>Stories by Jonathan Casarrubias on Medium</title>
            <link>https://medium.com/@jcasarrubias?source=rss-4298d94ff69b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:16:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jcasarrubias/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Real-Time Applications With Angular 2, LoopBack and FireLoop.io]]></title>
            <link>https://medium.com/@jcasarrubias/building-real-time-applications-with-angular-2-loopback-and-fireloop-io-6265ac09992c?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6265ac09992c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Thu, 13 Oct 2016 14:02:16 GMT</pubDate>
            <atom:updated>2016-10-13T14:02:16.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bUG_awKeHcG1gH9Vmzoqw.jpeg" /></figure><p>Previously on <a href="http://mean.expert/2016/09/17/angular-2-chart-component-revised/">How To Build A Chart Component in Angular 2 and D3 (Revised Version)</a> I explained how to create a chart component with <a href="http://angular.io/">Angular 2</a> and <a href="https://d3js.org/">D3</a>, I know I promised I would create a blog for <a href="https://github.com/swimlane/ng2d3">ng2d3</a> and I will, but first.</p><p>There is something very important I need to announce, I’m very excited to publish now that an amazing feature has been added into the <a href="https://www.npmjs.com/package/@mean-expert/loopback-sdk-builder">LoopBack SDK Builder</a>; its name <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a>!!!!!</p><p>[Public Applauses and Expectation in the Background]</p><h3>PRESENTING FIRELOOP.IO</h3><p><a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> is a new Real-Time Platform built on top of <a href="http://loopback.io/">LoopBack</a> that replaces the standard REST API and transforms this wonderful and mature framework into a powerful Real-Time Engine.</p><p>I want to keep this article technical and not to focus on other details, if you want to read about the motivation, comparison between other frameworks, etc. Please <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">READ HERE</a></p><h3>PROJECT DESCRIPTION</h3><p>Now that you have an idea of what <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> is, I want to show you how to build a Real-Time Todo Application by using these technologies.</p><p>I always decide to use a Todo application when the technology is so new or important that for now the actual result application is not really significative, this will allow new developers to easily understand rather than using more complex examples.</p><h3>REQUIREMENTS</h3><p>We are going to build a Real-Time Application using <a href="http://angular.io/">Angular 2</a>, <a href="http://loopback.io/">LoopBack</a> and <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a>, therefore you will need the following global packages to be installed.</p><pre>$ npm install -g strongloop angular-cli</pre><h3>CREATE API</h3><p>First we are going to create our <a href="http://loopback.io/">LoopBack</a> API and then we will install <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> on top to enable the Real-Time capabilities.</p><pre>$ mkdir todo-project &amp;&amp; cd todo-project<br>$ mkdir todo-api &amp;&amp; cd todo-api<br>$ slc loopback</pre><pre> _ — — -_ <br> | | ╭──────────────────────────╮<br> | — (o) — | │ Let’s create a LoopBack │<br> ` — — — — -´ │ application! │<br> ( _´U`_ ) ╰──────────────────────────╯<br> /___A___\ /<br> | ~ | <br> __’.___.’__ <br> ´ ` |° ´ Y ` </pre><pre>? What’s the name of your application? todo-api<br>? What kind of application do you have in mind? api-server (A LoopBack API server with local User auth)<br>? Which version of LoopBack would you like to use? 2.x</pre><h4>INSTALL FIRELOOP MODULES</h4><p>Now we need to install and configure the required modules for <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> to work.</p><pre>$ npm install — save @mean-expert/{loopback-sdk-builder,loopback-component-realtime}</pre><p>If you did not read the motivation just yet I need to clarify that one of the reasons I decided to bundle and brand <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> is because I want you to avoid all of these configurations, but until I work in a command line tool, you will need to manually do the following configurations:</p><blockquote>But before, I can promise that when I finish the command tool; you will need to install only 1 package with zero configurations. Therefore I will be revisiting this article avoiding all of the following.</blockquote><h4>CONFIGURE REAL-TIME MODULE</h4><p>Open the file server/server.js and modify the app.start method as follows:</p><pre>app.start = function() {<br> // start the web server<br> var server = app.listen(function() {<br> app.emit(‘started’, server);<br> var baseUrl = app.get(‘url’).replace(/\/$/, ‘’);<br> console.log(‘Web server listening at: %s’, baseUrl);<br> if (app.get(‘loopback-component-explorer’)) {<br> var explorerPath = app.get(‘loopback-component-explorer’).mountPath;<br> console.log(‘Browse your REST API at %s%s’, baseUrl, explorerPath);<br> }<br> });<br> return server;<br>};</pre><p>Now open the file server/component-config.json and modify as follows:</p><pre>{<br> “loopback-component-explorer”: {<br> “mountPath”: “/explorer”<br> },<br> “@mean-expert/loopback-component-realtime”: {<br> “auth”: false // For this example, we will see authentication in another post.<br> }<br>}</pre><h4>CONFIGURE SDK BUILDER</h4><p>Open the file package.json and add the following within the scripts section:</p><pre>{<br> “name”: “todo-api”,<br> “version”: “1.0.0”,<br> “main”: “server/server.js”,<br> “scripts”: {<br> …<br> “build:sdk”: “./node_modules/.bin/lb-sdk server/server ../todo-app/src/app/shared/sdk”<br> },<br> …<br>}</pre><p>Ok, now we have the Back-End configurations in place, but before we move to the <a href="http://angular.io/">Angular 2</a> part, lets just create a simple Todo Model.</p><h4>CREATE TODO MODEL</h4><pre>$ slc loopback:model Todo<br>? Enter the model name: Todo<br>? Select the data-source to attach Todo to: db (memory)<br>? Select models base class PersistedModel<br>? Expose Todo via the REST API? Yes<br>? Custom plural form (used to build REST URL): todos<br>? Common model or server only? common<br>Lets add some Todo properties now.</pre><pre>Enter an empty property name when done.<br>? Property name: text<br>? Property type: string<br>? Required? Yes<br>? Default value[leave blank for none]:</pre><h3>CREATE ANGULAR 2 APPLICATION</h3><pre>$ cd ../<br>$ ng new todo-app<br>Visit <a href="http://ember-cli.com/user-guide/#watchman">http://ember-cli.com/user-guide/#watchman</a> for more info.<br>installing ng2<br> create .editorconfig<br> create README.md<br> create src/app/app.component.css<br> create src/app/app.component.html<br> create src/app/app.component.spec.ts<br> create src/app/app.component.ts<br> create src/app/app.module.ts<br> create src/app/index.ts<br> create src/app/shared/index.ts<br> create src/assets/.gitkeep<br> create src/assets/.npmignore<br> create src/environments/environment.prod.ts<br> create src/environments/environment.ts<br> create src/favicon.ico<br> create src/index.html<br> create src/main.ts<br> create src/polyfills.ts<br> create src/styles.css<br> create src/test.ts<br> create src/tsconfig.json<br> create src/typings.d.ts<br> create angular-cli.json<br> create e2e/app.e2e-spec.ts<br> create e2e/app.po.ts<br> create e2e/tsconfig.json<br> create .gitignore<br> create karma.conf.js<br> create package.json<br> create protractor.conf.js<br> create tslint.json<br>Successfully initialized git.<br>Installing packages for tooling via npm.</pre><h3>BUILD FIRELOOP SDK</h3><pre>$ cd todo-api<br>$ npm run build:sdk</pre><h3>INSTALL FIRELOOP SDK DEPENDENCIES</h3><pre>$ cd ../todo-app<br>$ npm install — save socket.io-client @types/socket.io-client</pre><p>Open the file todo-app/src/tsconfig.json and add a new types section:</p><pre>{<br> “compilerOptions”: {<br> ….<br> “types”: [<br> “socket.io-client”<br> ]<br> }<br>}</pre><p>And to finish all of these configurations, lets just install the SDK Module within our <a href="http://angular.io/">Angular 2</a> Application by opening the todo-app/src/app/app.module.tsand modify as follows:</p><pre>import { BrowserModule } from ‘@angular/platform-browser’;<br>import { NgModule } from ‘@angular/core’;<br>import { FormsModule } from ‘@angular/forms’;<br>import { HttpModule } from ‘@angular/http’;<br>import { SDKModule } from ‘./shared/sdk’;<br>import { AppComponent } from ‘./app.component’;</pre><pre>@NgModule({<br> declarations: [<br> AppComponent<br> ],<br> imports: [<br> BrowserModule,<br> FormsModule,<br> HttpModule,<br> SDKModule.forRoot()<br> ],<br> providers: [],<br> bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><h3>DISCLAIMER</h3><p>Wow, I know that was a lot of configurations… Specially difficult if you are attracted by the final result, but you are totally new to <a href="http://loopback.io/">LoopBack</a> or even <a href="http://angular.io/">Angular 2</a>.</p><p>This is a perfect example of why I’m creating <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop.io</a> (Not just the <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> module but the Framework), because this is not about competing vs<a href="http://loopback.io/">LoopBack</a>; This is more about making a greater experience while working with <a href="http://loopback.io/">LoopBack</a> but also by creating a better learning curve experience, providing with a single command that setup everything. Until that happen, you now know how it is manually configured.</p><p>So… If you make it until here, I appreciate it and promise in a not so far future I’ll make everything easier in order to allow you to focus in the fun part:</p><h3>ADD TODO LOGIC</h3><p>Finally, its time to have some fun!!! For so, lets modify our app.component.ts file in order to be connected with <a href="http://loopback.io/">LoopBack</a> and the <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> module by adding the following methods:</p><pre>import { Component } from ‘@angular/core’;<br>import { Todo, FireLoopRef } from ‘./shared/sdk/models’;<br>import { RealTime } from ‘./shared/sdk/services’;</pre><pre>@Component({<br> selector: ‘app-root’,<br> templateUrl: ‘./app.component.html’,<br> styleUrls: [‘./app.component.css’]<br>})</pre><pre>export class AppComponent {</pre><pre> title = ‘TODO Application’;</pre><pre> private todo : Todo = new Todo();<br> private reference : FireLoopRef&lt;Todo&gt;;</pre><pre> constructor(private rt: RealTime) {<br> this.reference = this.rt.FireLoop.ref&lt;Todo&gt;(Todo);<br> }</pre><pre> add(): void {<br> this.reference.create(this.todo).subscribe(() =&gt; this.todo = new Todo());<br> }</pre><pre> update(todo: Todo): void {<br> this.reference.upsert(todo).subscribe();<br> }</pre><pre> remove(todo: Todo): void {<br> this.reference.remove(todo).subscribe();<br> }<br>}</pre><p>Really simple huh? Actually I think it is really self-explanatory, but I want to talk about some details:</p><h4>MODELS AND FIRELOOP REFERENCES ARE ALL YOU NEED</h4><p>Yes!!! You read right, <em>but… What exactly does that mean?</em> Well… That means that now you can avoid the creation of a bunch of references for properties and methods, as we are used to.</p><p>For instance, you usually would create a private todos: Todo[] = new Array&lt;Todo&gt;() list, but now that is totally unnecessary.</p><p>The <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> Reference we created is able to be in sync with the server for any list modification and with some <a href="http://angular.io/">Angular 2</a> help, you will be able to directly render it as follows:</p><h3>UPDATE APP.COMPONENT.HTML</h3><pre>&lt;h1&gt;<br> {{title}}<br>&lt;/h1&gt;<br>&lt;form (submit)=”add()”&gt;<br> &lt;input type=”text” name=”todo” [(ngModel)]=”todo.text” placeholder=”Add Todo” /&gt;<br> &lt;button&gt;Add&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;ul&gt;<br> &lt;li *ngFor=”let todo of reference.on(‘changes’) | async”&gt;<br> &lt;input type=”text” name=”todo” [(ngModel)]=”todo.text” /&gt;<br> &lt;button (click)=”update(todo)”&gt;update&lt;/button&gt;<br> &lt;button (click)=”remove(todo)”&gt;remove&lt;/button&gt;<br> &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Again, this is a really straightforward example but I want to focus in something:</p><pre>&lt;li *ngFor=”let todo of reference.on(‘changes’) | async”&gt;</pre><p>As you can see we are using the <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> reference to listen changes and by using the async pipe, <a href="http://angular.io/">Angular 2</a> will render all of our Todos within our application view.</p><p>But… that is not the ideal and there are several reasons that can be listed, from performance to usability.</p><p>So… What can be done?</p><p>If you have some experience with <a href="http://angular.io/">Angular 2</a> you may already have the assumption that the reference.on(&#39;changes&#39;) is actually returning an Observablethat we can reference it and use it instead.</p><pre>…<br>export class AppComponent {<br> …<br> private todo : Todo = new Todo();<br> private todos : Observable&lt;Todo[]&gt;;<br> private reference : FireLoopRef&lt;Todo&gt;;</pre><pre> constructor(private rt: RealTime) {<br> this.reference = this.rt.FireLoop.ref&lt;Todo&gt;(Todo);<br> this.todos = this.reference.on(‘changes’);<br> }<br> … <br>}</pre><pre>&lt;li *ngFor=”let todo of todos | async”&gt;</pre><p>This is not only better for performance, but it allows you to request what you developer or your end users actually require. What is that? Query Language.</p><pre>…<br>export class AppComponent {<br> …<br> constructor(private rt: RealTime) {<br> this.reference = this.rt.FireLoop.ref&lt;Todo&gt;(Todo);<br> this.todos = this.reference.on(‘changes’, {<br> offset: 0,<br> limit: 10,<br> order: ‘id DESC’<br> });<br> }<br> … <br>}</pre><p>This open a new world of possibilities because you are now in sync with the server, but you get what this specific client needs, which is awesome for real time lists, chats, reports, etc.</p><p>Again if you are new to <a href="http://loopback.io/">LoopBack</a> and you want to know what filters are available, please check the <a href="http://loopback.io/doc/en/lb2/Querying-data.html">FOLLOWING INFORMATION</a> and note that you care about the filters, but not the methods syntax, remember <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> is a totally new interface.</p><p>If you want to know more about <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop</a> syntax please <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">READ HERE</a>.</p><h3>FIX ANGULAR CLI REQUIRE TYPE</h3><p>At the moment I write this article, the <a href="http://angular.io/">Angular 2</a> CLI Tool generates a console error, that if I don’t talk about it; it may seems this example has bugs. But, truth is the error is displayed from a vanilla installation, but how to fix it?</p><p>If you are getting a Cannot find name &#39;require&#39; error, the you will need just to open the src/typings.d.ts file and add the following line:</p><pre>declare var require: any;</pre><p>That is all; you should be able to test our Real-Time Todo Application without any error in the console.</p><h3>TEST</h3><p>If you start both, the front end/ back end servers you should be able to see the following result:</p><p>Run Server</p><pre>$ cd to/todo-project/todo-api<br>$ node .</pre><p>Run Client</p><pre>$ cd to/todo-project/todo-app<br>$ ng serve</pre><p>Open 2 browser tabs on http://127.0.0.1:4200 and have your Real-Time Todo App up and running.</p><h3>WHAT IS NEXT?</h3><p>Well, there is a good amount of work ahead by building the <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/8.-(NEW)-FireLoop-API">FireLoop.io</a> Framework, one of my priorities is to integrate with <a href="http://angular.io/">Angular 2</a> Universal, so… My next steps will be to deliver the last <a href="https://github.com/swimlane/ng2d3">ng2d3</a> article and after I will be presenting improvements and new integrations so you can build even faster and better <a href="http://angular.io/">Angular 2</a> Applications.</p><p>If you like this series and want be aware of next releases and new packages, follow me on Twitter <a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6265ac09992c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Easy Stats with Angular 2, D3 and LoopBack (Revised Version)]]></title>
            <link>https://medium.com/@jcasarrubias/building-easy-stats-with-angular-2-d3-and-loopback-revised-version-4997a62565c6?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4997a62565c6</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Mon, 12 Sep 2016 14:03:11 GMT</pubDate>
            <atom:updated>2016-09-12T14:03:11.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dkOantk8WN9e5gPq.jpg" /></figure><p>Previously on <a href="http://mean.expert/2016/09/03/loopback-sdk-builder">PRESENTING: LoopBack SDK Builder V2</a> I presented the first stable release of The <a href="http://npmjs.org/package/@mean-expert/loopback-sdk-builder">SDK Builder</a> that seamlessly and beautifully integrates The<a href="http://loopback.io/">IBM’s StrongLoop LoopBack Framework</a> with the <a href="http://angular.io/">Google’s Angular 2 Framework</a> that glued together allows you to build not only Web Pages but Desktop, Native Mobile, Progressive and IoT Applications.</p><p>Today I’m publishing a revised version of a previous article <a href="http://mean.expert/2016/04/25/angular-2-and-loopback/">Building Easy Stats with Angular 2, D3 and LoopBack</a> which after 5 months, many things have changed in the <a href="http://angular.io/">Angular 2</a> World and definitely requires a revision.</p><h3>PROJECT DESCRIPTION</h3><p>In this tutorial we are going to create an <a href="http://angular.io/">Angular 2</a> Application using the <a href="http://cli.angular.io/">Angular CLI</a> Tool, also we will create a StatModule using the final <a href="http://angular.io/">Angular 2</a> API.</p><p>We will also get datasets from the API we built in <a href="http://mean.expert/2016/04/13/loopback-stats-mixin">Part 1</a> and <a href="http://mean.expert/2016/04/21/loopback-stats-mixin-part2">Part 2</a>.</p><p>Later on, we will be using <a href="https://d3js.org/">D3</a> to create a chart component that will help us to represent the data we created in my previous posts.</p><h3>REQUIREMENTS</h3><ul><li><a href="http://nodejs.org/">NodeJS</a></li><li><a href="http://npmjs.org/">NPM</a></li><li><a href="http://cli.angular.io/">Angular CLI</a></li><li><a href="http://typescriptlang.org/">TypeScript</a></li><li>Follow <a href="http://mean.expert/2016/09/10/angular-2-and-loopback-revised/%22/2016/04/13/loopback-stats-mixin%22">Part 1</a> and <a href="http://mean.expert/2016/09/10/angular-2-and-loopback-revised/%22/2016/04/21/loopback-stats-mixin-part2%22">Part 2</a> if you care about how we got the datasets for the charts.</li></ul><h3>SETUP ANGULAR PROJECT</h3><p>We can start by installing the <a href="http://cli.angular.io/">Angular CLI</a> Tool, which can help you to scaffold your application making the essential configuration for you.</p><pre>$ npm install -g angular-cli<br>$ cd /to/project/root<br>$ ng new easy-stats-app</pre><p>The command above will create a new folder with a new <a href="http://angular.io/">Angular 2</a> Application in place, but there is a dependency always needed when you are going to consume a remote API that is not included within the <a href="http://angular.io/">Angular 2</a> core: The @angular/http module. Thus you will need to install it and this is a very good moment to do it.</p><pre>$ cd easy-stats-app<br>$ npm install — save @angular/http</pre><h3>INSTALL SDK BUILDER</h3><p>Now that we have our application set, we want to start consuming the endpoints we created in <a href="http://mean.expert/2016/09/10/angular-2-and-loopback-revised/%22/2016/04/13/loopback-stats-mixin%22">Part 1</a> and <a href="http://mean.expert/2016/09/10/angular-2-and-loopback-revised/%22/2016/04/21/loopback-stats-mixin-part2%22">Part 2</a>, but this time we will consume this endpoints using an automatically created Software Development Kit</p><pre>$ cd ../easy-stats-api/<br>$ npm install — save-dev @mean-expert/loopback-sdk-builder</pre><h3>CREATE SDK</h3><p>The <a href="https://www.npmjs.com/package/@mean-expert/loopback-sdk-builder">LoopBack SDK Builder</a> is able to analyze your API and automatically create a fully working SDK that allows you to avoid spending time in creating<a href="http://typescriptlang.org/">TypeScript</a>‘s Interfaces, Classes and <a href="http://angular.io/">Angular 2</a>‘s Services; allowing you to start writing your application right away.</p><p>To achieve that you need to create a new NPM Script Command as follows:</p><p>easy-stats-api/package.json</p><pre>{<br> …<br> “scripts”: {<br> …<br> “build:sdk”: “./node_modules/.bin/lb-sdk server/server.js ../easy-stats-app/src/app/shared/sdk”<br> }<br> …<br>}</pre><p>Save the file and then from a terminal just run the following command:</p><pre>$ npm run build:sdk</pre><p>In a couple of seconds you will see a list of generated files within your <a href="http://angular.io/">Angular 2</a> Application. If you want to know in more detail about the libraries the<a href="https://www.npmjs.com/package/@mean-expert/loopback-sdk-builder">LoopBack SDK Builder</a> just created, then you can see the following <a href="https://github.com/mean-expert-official/loopback-sdk-builder/wiki/3.-SDK-Components">SDK Components Link</a>.</p><h3>INSTALL ANGULAR 2 SDK</h3><p>By this moment, you should already have within your <a href="http://angular.io/">Angular 2</a> Application Directory; all the files related to your <a href="http://angular.io/">Angular 2</a> SDK, but you still need to tell Angular that there is a module you want to use.</p><p>easy-stats-app/src/app/app.module.ts</p><pre>import { BrowserModule } from ‘@angular/platform-browser’;<br>import { NgModule } from ‘@angular/core’;<br>import { FormsModule } from ‘@angular/forms’;<br>import { HttpModule } from ‘@angular/http’;</pre><pre>import { AppComponent } from ‘./app.component’;<br>// Import the SDK Module<br>import { SDKModule } from ‘./shared/sdk’; </pre><pre>@NgModule({<br> declarations: [<br> AppComponent<br> ],<br> imports: [<br> BrowserModule,<br> FormsModule,<br> HttpModule,<br> // Tell Angular we want the SDKModule to be available app wide<br> SDKModule.forRoot()<br> ],<br> providers: [],<br> bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>For those using WebPack, you may need to import the module directly from the Index within the SDK directory as follows:</p><pre>import { SDKModule } from ‘./shared/sdk/index’;</pre><p>That’s it; you are now able to start consuming your API and start writing <a href="http://angular.io/">Angular 2</a> Modules. So, lets create one.</p><h3>CREATE STAT MODULE</h3><p>A great thing of the <a href="http://cli.angular.io/">Angular CLI</a> is that you don’t need to manually create modules and components, but use commands to automatically create these.</p><pre>$ ng generate module Stat<br>installing module<br> create src/app/stat/stat.module.ts<br>installing component<br> create src/app/stat/stat.component.css<br> create src/app/stat/stat.component.html<br> create src/app/stat/stat.component.spec.ts<br> create src/app/stat/stat.component.ts</pre><h3>UPDATE STATCOMPONENT</h3><p>We need to update our StatComponent that will get the datasets from our LoopBack application, for this we need to import the Customer Model and CustomerApi Service from the SDK.</p><p>Then you can start creating Customer Model instances that are component scope binded, this means that once you define a customer property, you will also have access within your component template and use one way or two way data bindings as required.</p><p>Also you are able to set the right type, this will contain the schema you define in your API Models, then you just need to inject the CustomerApi Service and start connecting everything together.</p><pre>import { Component, OnInit } from ‘@angular/core’;<br>import { Customer } from ‘../shared/sdk/models’;<br>import { CustomerApi } from ‘../shared/sdk/services’;</pre><pre>@Component({<br> selector: ‘app-stat’,<br> templateUrl: ‘./stat.component.html’,<br> styleUrls: [‘./stat.component.css’]<br>})<br>export class StatComponent implements OnInit {</pre><pre> private customer: Customer = new Customer();<br> private range: string = ‘weekly’;</pre><pre> constructor(private customerApi: CustomerApi) { }</pre><pre> ngOnInit() {<br> }</pre><pre> getStats() {<br> this.customerApi.customerStatsWrapper(this.customer.id, this.range)<br> .subscribe((stats: any[]) =&gt; console.log(stats));<br> }<br>}</pre><p>So, I know at this moment this seems like black magic and you may be asking, where does these services come from and how come that we are making calls just now?</p><p>Is almost magic, but truth is that the <a href="https://www.npmjs.com/package/@mean-expert/loopback-sdk-builder">LoopBack SDK Builder</a> is able to navigate all your Models and REST Services you defined in <a href="http://loopback.io/">LoopBack</a> and then create for you everything you need just to tie pieces together.</p><p>Easy, huh?. Well… what is that private customerApi: CustomerApi after all? If you are brand new into the <a href="http://angular.io/">Angular 2</a> World, then you should know that the framework will inject every dependency instance you need, when defined in the constructor of the component… In other words, is like saying <a href="http://angular.io/">Angular 2</a> that you want to use the CustomerApi that comes from the SDK and you need the framework to create an instance for that dependency and then inject it within your component. This design pattern is called, <a href="https://angular.io/docs/ts/latest/guide/dependency-injection.html">Dependency Injection</a>.</p><h3>UPDATING THE VIEW</h3><p>Modify the stat.component.html file adding the following markup:</p><pre>&lt;h1&gt;Easy Stats&lt;/h1&gt;<br>&lt;label for=”customerId”&gt;Customer Id:&lt;/label&gt;<br>&lt;input name=”customerId” type=”text” [(ngModel)]=”customer.id” placeholder=”customerId” /&gt;<br>&lt;label for=”range”&gt;Range:&lt;/label&gt;<br>&lt;input name=”range” type=”text” [(ngModel)]=”range” placeholder=”range” /&gt;<br>&lt;button (click)=”getStats()”&gt;Get Stats&lt;/button&gt;</pre><h3>UPDATE APP.COMPONENT.HTML</h3><p>For now, we will call our StatComponent directly from the app.component.html</p><pre>&lt;h1&gt;<br> {{title}}<br>&lt;/h1&gt;<br>&lt;app-stat&gt;&lt;/app-stat&gt;</pre><h3>BEFORE TEST</h3><p>Before testing the app you need to make sure your API is running and you have set a number of customers and orders.</p><p>Also, we did not setup any datasource to our API, if you stop the process you will lose your data, therefore you won’t be able to test this app.</p><p>To avoid that behavior you will need to <a href="https://docs.strongloop.com/display/public/LB/datasources.json">Setup a DataSource in LoopBack</a>.</p><h3>TEST</h3><p>If you start the server again $ ng serve you will be able to see a form that will help you get the information from the API we built.</p><p>For now, we are able to verify the information on the Browser’s Console.</p><h3>WHAT IS NEXT?</h3><p>In my next blog post I will publish a revised version of my previous article <a href="http://localhost:4000/2016/05/02/angular-2-chart-component/">How To Build A Chart Component in Angular 2 and D3</a> continuing the application we just developed.</p><p>If you like this series and want be aware of next releases and new packages, follow me on Twitter <a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4997a62565c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide For Native App Development]]></title>
            <link>https://medium.com/@jcasarrubias/the-ultimate-guide-for-native-app-development-878bd40abadb?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/878bd40abadb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nativescript]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Mon, 30 May 2016 14:19:34 GMT</pubDate>
            <atom:updated>2016-05-30T14:19:34.502Z</atom:updated>
            <content:encoded><![CDATA[<p>The Ultimate Guide For Native App Development</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*jJIiRGEJpXD4m77o.jpg" /><figcaption>The Ultimate Guide For Native App Development</figcaption></figure><p>Previously on <a href="http://mean.expert/2016/05/21/angular-2-component-communication/">Angular 2: How Do Components Communicate</a> I explained the different methods for Angular 2 Components to communicate between each other, either from parent to child, child to parent or by using injectable services and <a href="http://reactivex.io/">RxJS</a>.</p><p><strong>Now I want you to read this very carefully</strong>… <em>What I’m going to show you today is something that no one has ever done or even tried before.</em></p><p>Today for the very first time I’m going to show you how to integrate <a href="http://mongodb.org/">MongoDB</a> with the <a href="http://strongloop.com/">IBM StrongLoop’s LoopBack Framework</a>, <a href="http://nativescript.org/">NativeScript 2</a> and <a href="http://angular.io/">Angular 2</a> to build truly Native Mobile Applications using the <strong>MEAN Stack</strong> in less than 50 lines of code!!!</p><p>[Public Applauses and Expectation in the Background]</p><h3>Project Description</h3><p>The objective of this tutorial is to show you a wonderful way to build truly native apps using the MEAN Stack, therefore I don’t want to create a really complex project, otherwise things can get a little bit overwhelming.</p><p>So.. I know everybody has ever built a Todo List App and that is why I want to use this as demo application, because in that way you don’t lose time and effort understanding a more complex application.</p><p>Instead we will focus on the technologies and the setup so you can build your own Native Mobile Applications using the MEAN Stack like a <a href="http://mean.expert/">MEAN Expert</a>.</p><h3>Technology Stack</h3><ul><li><a href="https://www.mongodb.com/">MongoDB</a>.- Building on the Best of Relational with the Innovations of NoSQL.</li><li><a href="http://loopback.io/">LoopBack</a>.- The Node.js API Framework.</li><li><a href="http://angular.io/">Angular 2</a>.- Development platform for building mobile and desktop applications.</li><li><a href="http://nativescript.org/">NativeScript 2</a>.- Truly native mobile apps with Angular.</li></ul><h3>Requirements</h3><ul><li><a href="https://nodejs.org/">Install NodeJS and NPM</a></li><li><a href="https://docs.mongodb.com/getting-started/shell/installation/">Install MongoDB</a></li></ul><h3>GitHub Example Code Repository</h3><p><a href="http://goo.gl/TWWG1h">StrongLoop and NativeScript Integration</a></p><h3>Setup Environment</h3><p>Ok since you already have installed the environment stack, now we need to install the platforms needed for this project, for this we are going to use <a href="http://npmjs.com/">NPM</a>.</p><p>$ npm install -g strongloop nativescript</p><h3>Setup DataBase</h3><p>Once you have installed and running <a href="https://www.mongodb.com/">MongoDB</a> you need to setup an instance by using the following commands in a terminal.</p><pre>$ mongo</pre><pre>&gt; use todo-db<br>switched to db todo-db</pre><pre>&gt; db.createUser({ user: ‘todo-user’, pwd: ‘todo-pass’, roles: [‘readWrite’] });</pre><p>Of course you can do this in your local machine or in a remote server, also use more secure credentials that are not for demo purposes.</p><h3>Setup REST API Project</h3><pre>$ mkdir todo<br>$ mkdir todo/todo-api<br>$ cd todo/todo-api<br>$ slc loopback<br></pre><pre> _ — — -_<br> | | . — — — — — — — — — — — — — .<br> | — (o) — | | Let’s create a LoopBack |<br> ` — — — — -´ | application! |<br> ( _´U`_ ) ‘ — — — — — — — — — — — — — ‘<br> /___A___\ <br> | ~ | <br> __’.___.’__ <br> ´ ` |° ´ Y ` </pre><pre>? What’s the name of your application? todo-api<br>? What kind of application do you have in mind? api-server (A LoopBack API server with local User auth)<br>Generating .yo-rc.json<br></pre><pre>I’m all done. Running npm install for you to install the required dependencies. If this fails, try running the command yourself.<br></pre><pre> create .editorconfig<br> create .jshintignore<br> create .jshintrc<br> create server/boot/root.js<br> create server/middleware.json<br> create server/middleware.production.json<br> create server/server.js<br> create README.md<br> create server/boot/authentication.js<br> create .gitignore<br> create client/README.md<br>todo-api@1.0.0 /Volumes/backup/development/www/mean.expert/examples/todo/todo-api</pre><pre>Next steps:</pre><pre> Create a model in your app<br> $ slc loopback:model</pre><pre> Compose your API, run, deploy, profile, and monitor it with Arc<br> $ slc arc</pre><pre> Run the app<br> $ node .</pre><p>We have just created a <a href="http://loopback.io/">LoopBack Application</a>, if you run the $ node . command, you will have a fully working RESTful API running in your machine/server that includes built in User Model, Authentication mechanism and API Explorer. But we still need to configure a datasource to connect with our MongoDB Instance.</p><p>For those who doesn’t know The <a href="http://strongloop.com/">StrongLoop</a>‘s <a href="http://loopback.io/">LoopBack Framework</a> but you come from languages like <a href="http://php.net/">PHP</a> or <a href="https://www.ruby-lang.org/en/">Ruby Lang</a> and you use <a href="https://laravel.com/">Laravel</a>, <a href="http://rubyonrails.org/">Ruby on Rails</a> or from any language but you know the <a href="https://en.wikipedia.org/wiki/Active_record_pattern">Active Record Pattern</a>, well.. if you love these frameworks, or you love the<a href="https://en.wikipedia.org/wiki/Active_record_pattern">Active Record Pattern</a>, this is the framework in node that implements it the best, so you should be loving it by now.</p><h3>Configure DataSource</h3><p>In order to persist the information we create from the Client Application; we need to create a datasource that connects with MongoDB.</p><pre>$ slc loopback:datasource<br>? Enter the data-source name: mongodb<br>? Select the connector for mongodb: MongoDB (supported by StrongLoop)<br>Connector-specific configuration:<br>? host: localhost<br>? port: 27017<br>? user: todo-user<br>? password: *********<br>? database: todo-db<br>? Install loopback-connector-mongodb@^1.4 Yes<br>└─ loopback-connector-mongodb@1.15.2</pre><h3>Create Todo Model</h3><p>Remember we are creating a really simple app, since our goal is to get to know how to build truly native applications using the MEAN Stack, so for this project we are going to create just a model named Todo.</p><p>But if you like this post and you request me on <a href="http://twitter.com/johncasarrubias">Twitter</a> I can build a much more complex application with relationships, acls and more.</p><pre>$ slc loopback:model Todo<br>? Enter the model name: Todo<br>? Select the data-source to attach Todo to: mongodb (mongodb)<br>? Select model’s base class PersistedModel<br>? Expose Todo via the REST API? Yes<br>? Custom plural form (used to build REST URL): todos<br>? Common model or server only? common<br>Let’s add some Todo properties now.</pre><pre>Enter an empty property name when done.<br>? Property name: text<br> invoke loopback:property<br>? Property type: string<br>? Required? Yes<br>? Default value[leave blank for none]: </pre><pre>Let’s add another Todo property.<br>Enter an empty property name when done.<br>? Property name:</pre><h3>Configure The NativeScript 2 SDK Builder</h3><p>A wonderful feature from the <a href="http://loopback.io/">LoopBack Framework</a> is the loopback-sdk-angular which automatically maps your RESTful API’s endpoints and provides you with a set of services compatible with <a href="https://angularjs.org/">AngularJS 1</a>.</p><p><em>Hey wait, but aren’t we going to use NativeScript 2 with Angular 2</em>? Well, thanks to community contributions in order to support <a href="http://angular.io/">Angular 2-Beta</a> and that I forked the module and added support also for <a href="http://angular.io/">Angular 2-RC</a> and for <a href="http://nativescript.org/">NativeScript 2</a>, now everyone can automatically build an SDK for NativeScript with the minimum effort.</p><h4>Modify package.json by adding</h4><pre>{<br> “devDependencies”: {<br> “loopback-sdk-angular”: “github:jonathan-casarrubias/loopback-sdk-angular”,<br> “loopback-sdk-angular-cli”: “github:qeti/loopback-sdk-angular-cli”<br> }<br>}</pre><h4>Install Dev Dependencies</h4><pre>$ npm install</pre><h3>Create NativeScript Application</h3><p>Before we build the SDK lets first create our <a href="http://nativescript.org/">NativeScript 2 Application</a>.</p><p>But what is so fantastic about <a href="http://nativescript.org/">NativeScript 2</a>… Well these guys really did it. Finally we are able to build truly native mobile applications using JavaScript <a href="http://www.typescriptlang.org/">TypeScript</a>.</p><p>If we compare with other technologies like <a href="http://ionic.io/">Ionic</a> that renders over a WebView; <a href="http://nativescript.org/">NativeScript</a>renders using native components, giving you access to native API’s for the different mobile platforms like android and ios, what else can you ask for?</p><p>Lets create our <a href="http://nativescript.org/">NativeScript 2 Application</a>:</p><pre>$ cd ../<br>$ tns create todo-app --ng</pre><p>That will create a new folder todo-app with our <a href="http://nativescript.org/">NativeScript 2 Scaffolded Application</a> and the following folder structure:</p><pre>$ ls -la<br>drwxr-xr-x 4 user staff 136 May 25 18:33 .<br>drwxr-xr-x 8 user staff 272 May 25 16:38 ..<br>drwxr-xr-x 13 user staff 442 May 25 18:35 todo-api<br>drwxr-xr-x 9 user staff 306 May 25 18:33 todo-app</pre><h3>Build SDK</h3><p>It is time to do some magic and automatically create a SDK that will allow us to call every method within our backend from our mobile application, saving us hours of development in terms of client services.</p><pre>$ mkdir todo-app/app/sdk<br>$ cd todo-api<br>$ ./node_modules/loopback-sdk-angular-cli/bin/lb-ng server/server.js ../todo-app/app/sdk/lb.services.ts -l nativescript2</pre><p>Wow!!! that’s it.. <em>HABEMUS SDK</em>… brilliant!! we just saved ourselves hours of bugs, pain and development in terms of building client services, by now you are a <em>Super HERO</em> and you built a set of fully working API services with full support for NativeScript 2 SDK in place.<br>[Applauses and Cheering sounds in the background]</p><p>Actually… Do you remember coding anything to have a fully working REST API or Client SDK? I know you won’t… But don’t worry if you feel your developer skills has not been challenged just yet, there are plenty of challenges to come.</p><p>Now if you are curious and open the sdk file todo-app/app/sdk/lb.services.ts you will see it comes with a set of @Injectable services fully compatible with the Angular 2-RC Version and also with NativeScript 2 out of the box.</p><p><em>Important: If you want to build a web application that will render in a browser, then you should use -l angular2 when building the sdk</em>.</p><h3>Install @angular/http</h3><p>If you are using <a href="http://code.visualstudio.com/">Visual Studio Code</a> or any IDE with plugings or support for <a href="http://www.typescriptlang.org/">TypeScript</a>… You should be able to see the error mark referring to the missing HTTP Library from @angular, so lets install the dependency.</p><pre>$ cd ../todo-app<br>$ npm install — save @angular/http</pre><h3>Develop Mobile Application</h3><p>Finally we are set with everything we need to start building a native app, focusing ourselves in creating the views and adding some logic by using the NativeScript SDK we built just before.</p><p>Thanks to the fact that <a href="http://angular.io/">Angular 2</a> is not DOM dependent anymore, the guys from<a href="http://nativescript.org/">NativeScript</a> did a wonderful job by integrating this super cool platform to allow us build truly native apps using <a href="http://angular.io/">Angular 2</a>.</p><p>They provide with a set of directives that will allow us to build views by implementing native components from the device platform.</p><p>So, the first thing we want to do is to update the app.component.ts file from our todo-app project as follows:</p><pre>import { Component, OnInit } from “@angular/core”;<br>import { HTTP_PROVIDERS } from ‘@angular/http’;<br>import { Todo } from ‘./definitions’;<br>import { TodoApi } from ‘./sdk/lb.services’;</pre><pre>@Component({<br> selector: “my-app”,<br> templateUrl: ‘./app.component.html’,<br> providers: [TodoApi, HTTP_PROVIDERS],<br>})<br>export class AppComponent implements OnInit {</pre><pre> private todo: Todo = new Todo();<br> private list: Array&lt;Todo&gt; = new Array();</pre><pre> constructor(private ts: TodoApi) {<br> // Update with your API Address, IP in same network or DNS<br> this.ts.setBaseURL(‘http://192.168.0.1:3000/api’);<br> }</pre><pre> ngOnInit() {<br> this.getTodos();<br> }<br> <br> addTodo(): void {<br> this.ts.create(this.todo).subscribe(res =&gt; {<br> this.todo = new Todo();<br> this.list.push(res);<br> });<br> }<br> <br> getTodos(): void {<br> this.ts.find().subscribe(res =&gt; (this.list = res));<br> }<br>}</pre><p>As you can see this is a standard <a href="http://angular.io/">Angular 2</a> Component, other than that I know I said<a href="http://nativescript.org/">NativeScript</a> does not rely on the browser DOM, but then why are we calling an html file?.</p><p>They -NativeScript Team- say it is because it is better for IDE compatibility so you can have a nice mark up in every IDE, but at the end the components are not rendered in a web view, but it translates to native components.</p><p>So, here we are… by using import { TodoApi } from ‘./sdk/lb.services’ and by setting it in the providers configuration, <a href="http://angular.io/">Angular 2</a> will inject the service in the constructor, providing us to a full set of methods to communicate with the API.</p><p>If you don’t know what is an @Injectable Service please read my previous post:<a href="http://mean.expert/2016/05/21/angular-2-component-communication/">Angular 2: How do components communicate</a>.</p><h3>Exploring SDK</h3><p>Thanks to the fact that we exported a <a href="http://loopback.io/">LoopBack</a> SDK in <a href="http://www.typescriptlang.org/">TypeScript</a> we have all type of definitions that when using <a href="http://code.visualstudio.com/">Visual Studio Code</a> you will be able to explore the provided functionality by the generated sdk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zXKjeDDhHT7MWjKW.png" /></figure><p>Exploring NativeScript API SDK With VCode</p><p>As you can see you got all type of methods to connect with your <a href="http://loopback.io/">LoopBack Application</a> as if you were coding for the back end, really cool.</p><h3>Create Todo View</h3><p>We need to create a file named app.component.html and add the following directives:</p><pre>&lt;StackLayout&gt;<br> &lt;TextField [(ngModel)]=”todo.text” hint=”Add New Todo”&gt;&lt;/TextField&gt;<br> &lt;Button text=”Add” (tap)=”addTodo()”&gt;&lt;/Button&gt;<br> &lt;ListView [items]=”list”&gt;<br> &lt;template let-item=”item”&gt;<br> &lt;Label [text]=”item.text”&gt;&lt;/Label&gt;<br> &lt;/template&gt;<br> &lt;/ListView&gt;<br>&lt;/StackLayout&gt;</pre><p>Basically what we are doing is to create a view with a small form that will present aTextField a Button and a ListView components to present the data we get from the API or in order to create new todos.</p><h3>Clean CSS</h3><p>Remove every css style from the app.component.css file.</p><p>One thing, any css you use in your components will work similar to what I explained in the html view, it will be parsed to native when compiled.</p><h3>Test the App</h3><p>Come on… Really? That’s all? Well Yes.. for now!!! But with no more than 50 lines of code we built a truly native application that integrates a <a href="http://nodejs.org/">NodeJS</a> with <a href="http://nativescript.org/">NativeScript</a> by providing an<a href="http://strongloop.com/">IBM StrongLoop’s</a> <a href="http://loopback.io/">LoopBack Framework</a> Client SDK Out of the box, just like the big players, I mean.. You can now build Native Applications like a <a href="http://mean.expert/">MEAN Expert</a>.</p><p>It is time to test, so just make sure your API is up and running:</p><pre>$ cd todo-api<br>$ node .</pre><p>Open another terminal, connect your mobile device or setup a emulator and then:</p><pre>$ tns livesync [android|ios] — watch</pre><p>This command will add the platform to your project and all the required dependencies.</p><p>You should be able to see a native app with native components and should be able to start adding todos and persist these into the database.</p><p>It is not going to be a pretty app, I never promised to build the most pretty app in the world, but to show you that with less than 50 lines of code we could build an App with API integration SDK.</p><p>So.. you should see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZQtr4viwY8cHKKsN.png" /><figcaption>Playing with the Todo App</figcaption></figure><h3>Hilarious</h3><p>Really guys… we need to give some credit to the people who built these technologies, I mean… I know I’m the very first person integrating these so we could make such black magic, but… Together with these genius and a with great help of the community; we all have been building platforms and tools that really makes me think that the future of JavaScript is Now!!!</p><p>If you liked this super awesome tutorial and now you feel you can build native apps like an expert; please share this with your friends on <a href="http://twitter.com/">Twitter</a>, <a href="http://facebook.com/">Facebook</a>, boss, team, teachers, students, everyone need this kind of knowledge.</p><p>I really hope you enjoyed this post number 10 and if you want me to keep working on even better and more advanced tutorials, let me know.. leave a comment or tweet, I’m always willing to help :D</p><h3>What is next?</h3><p>In my next blog posts I want to explore more the <a href="http://nativescript.org/">NativeScript</a> world, more <a href="http://angular.io/">Angular 2</a> and also there are much more to learn about <a href="http://strongloop.com/">IBM’s StrongLoop</a> <a href="http://loopback.io/">LoopBack Framework</a>, because I mean.. we basically did not write a line of backend code lol.</p><p>If you like this series and want be aware of next releases and new packages, follow me on Twitter <a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878bd40abadb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 2: How Do Components Communicate]]></title>
            <link>https://medium.com/@jcasarrubias/angular-2-how-do-components-communicate-b2adafd6fc52?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2adafd6fc52</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Mon, 23 May 2016 14:16:09 GMT</pubDate>
            <atom:updated>2016-05-23T14:16:09.178Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular 2: How Do Components Communicate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*HCCceN1jNBrlsQW6.jpg" /></figure><p>Previously on <a href="http://mean.expert/2016/05/14/angular-2-container-component/">Angular 2: How to Build a Container Component</a> I explained how to create structural components that marks up the way a view is rendered by providing grid directives with a container, title, rows and items.</p><p>But before I move on and work in more advanced examples; I want to explain how do components communicate between each other in Angular 2.</p><h3>Types of Communication</h3><p>If you have some experience working with Angular 1, then you will know that there are some ways to communicate between controllers by using either the $rootScope, $scope, $emit,$broadcast or services. But now using Angular 2 we have slightly different ways to communicate between components.</p><p>When I first started to work with Angular 2 I quickly learned about the @Input and @Outputdecorators, I was also able to figure out that services will keep doing some of the job in this version, but I also found there are other interesting ways to communicate between components, so lets review these.</p><h3>Services</h3><p>The very first method I want to talk about is by using services, why? Well because I know many people will find familiar working with this and is a good way to feel you are in home.</p><p>The following snippet is an example of the most basic service form in Angular 2:</p><pre>import {Injectable} from ‘@angular/core’;<br>@Injectable()<br>export class MyService {<br> constructor() { }<br>}</pre><p>Basically, as you can see this is a regular class that will be exported as a module.</p><p>The only questionable feature in here is the @Injectable() decorator, which basically is a way to say angular that this service is good to be used in Dependency Injection (DI).</p><p>The following is an example of how would you call this service from any other component.</p><pre>import {Component, OnInit} from ‘@angular/core’;<br>import {MyService} from ‘./shared/my-service.ts’; // see angular.io/styleguide</pre><pre>@Component({<br> selector: ‘&lt;my-component&gt;&lt;/my-component&gt;’,<br> templateUrl: ‘app/name.component.html’,<br> providers: [MyService]<br>})</pre><pre>export class MyComponent implements OnInit {</pre><pre> constructor(private ms: MyService) {}</pre><pre> ngOnInit() { this.ms.doSomething(); }<br>}</pre><p>To use our service within any component is really simple, we import the module from whatever directory we may store it, then we say to Angular 2 that we want to use MyService as provider, this way Angular can create an instance for use and inject it in our constructor.</p><p>Then we are able to use our service instance by using this.ms anywhere in our component.</p><p>OK, so we know how to build a service so what? well we can build setters and getters to maintain some states of the application, or even some sort of information like when a user is logged, you can get the logged user anywhere in your application components.</p><h3>Services emitting Events using RXJS</h3><p>This may be a more advanced way to use services, let me continue with the logged example.</p><p>Within your Application you have 1 of many components living at the same time, one of these components is in charge to either communicate the user is logged in to other components or logged out.</p><p>Since a standard getter and setter won’t work because changes may occur after all components are already loaded, we need to set a listener that is watching for changes, but how?</p><h3>RJXS Subject</h3><pre>import {Injectable} from ‘@angular/core’;<br>import {Subject} from ‘rxjs’;<br>import {Logged} from ‘./definitions/logged.d.ts’;</pre><pre>@Injectable()<br>export class LoggedService {</pre><pre> private logged: Logged;<br> private subject: Subject&lt;Logged&gt; = new Subject&lt;Logged&gt;();</pre><pre> setLogged(logged: Logged): void {<br> this.logged = logged;<br> this.subject.next(logged);<br> }<br> <br> getLogged(): Subject&lt;Logged&gt; {<br> return this.subject;<br> }<br>}</pre><p>This example seems to be a little more complex, but it is not other than a way to emit and listen events, so we do not only have a setter and a getter that stores a local reference of logged but it will also send messages to any component that is register and listens for changes.</p><p>Now we would listen for changes as follow:</p><pre>import {Component, OnInit} from ‘@angular/core’;<br>import {LoggedService} from ‘./shared/logged-service.ts’;</pre><pre>@Component({<br> selector: ‘&lt;my-component&gt;&lt;/my-component&gt;’,<br> templateUrl: ‘app/name.component.html’,<br> providers: [LoggedService]<br>})</pre><pre>export class MyComponent implements OnInit {</pre><pre> constructor(private ls: LoggedService) {}</pre><pre> ngOnInit() {<br> // Will fire everytime other component use the setter this.ls.setLogged()<br> this.ls.getLogged().subscribe((logged: Logged) =&gt; {<br> console.log(‘Welcome %s’, logged.displayname);<br> });<br> }<br>}</pre><p>If we get our Injectable service and then we subscribe to the getLogged method within any of our components living in our application, we would be able to know when a user has been logged, when we could for example change the NavigationComponent View and display the user displayname instead of a sign in button.</p><p>I know this last example is a little more complex… So please leave a comment below for anything you need to be clarified.</p><h3>Input Properties (Parent -&gt; Child)</h3><p>The very first cool way to communicate between parents and children is by using @Inputproperties, which basically is type of communication Parent -&gt; Child.</p><p>The following snippet explains how to set a input property in a child component that will receive messages from the parent.</p><pre>import {Component, Input, OnInit} from ‘@angular/core’;</pre><pre>@Component({<br> selector: ‘child-component’,<br> template: `I’m {{ name }}`<br>})</pre><pre>export class ChildComponent implements OnInit {</pre><pre> @Input() name: string;</pre><pre> constructor() { }</pre><pre> ngOnInit() { }<br>}</pre><p>If we consider the following example, we will see how to implement the ChildComponent and how to communicate by using the @Input property.</p><pre>import {Component, OnInit} from ‘@angular/core’;<br>import {ChildComponent} from ‘./child-component.ts’;</pre><pre>@Component({<br> selector: ‘parent-component’,<br> template: `&lt;child-component [name]=”childName”&gt;&lt;/child-component&gt;`,<br> directives: [ChildComponent]<br>})</pre><pre>export class ParentComponent implements OnInit {<br> <br> private childName: string;<br> <br> constructor() { }</pre><pre> ngOnInit() { <br> this.childName = ‘Boo’;<br> }<br>}</pre><p>When implementing the ChildComponent within the ParentComponent and set thechildName as name by using the input property name, we communicate top to bottom a message that the result should be the ChildComponent saying something like: <em>I’m Boo</em>.</p><p>In this order of ideas we can also know when for some reason the ParentComponent changesChildComponent name, we can listen for those changes by using the component life cycle hookngOnChanges.</p><pre>import {Component, Input, SimpleChange} from ‘@angular/core’;</pre><pre>@Component({<br> selector: ‘child-component’,<br> template: `I’m {{ name }}`<br>})</pre><pre>export class ChildComponent {</pre><pre> @Input() name: string;</pre><pre> ngOnChanges(changes: SimpleChange) { }<br>}</pre><h3>Output Properties (Child -&gt; Parent)</h3><p>The following method is how ChildComponent communicates with ParentComponent by emitting events.</p><pre>@Component({<br> selector: ‘child-component’,<br> template: `I’m {{ name }}`<br>})</pre><pre>export class ChildComponent {</pre><pre> @Input() name: string;<br> @Output() cry: EventEmitter&lt;boolean&gt; = new EventEmitter&lt;boolean&gt;();</pre><pre> ngOnChanges(changes: SimpleChange) { }<br> <br> isHungry() {<br> this.cry.next(true);<br> }<br>}</pre><p>Since the ChildComponent is now able to emit the cry event when is hungry, now asParentComponent we need to set a listener for that event.</p><pre>import {Component, OnInit} from ‘@angular/core’;<br>import {ChildComponent} from ‘./child-component.ts’;</pre><pre>@Component({<br> selector: ‘parent-component’,<br> template: `&lt;child-component [name]=”childName” (cry)=”isChildCrying($event)”&gt;&lt;/child-component&gt;`,<br> directives: [ChildComponent]<br>})</pre><pre>export class ParentComponent implements OnInit {<br> <br> private childName: string;<br> <br> constructor() { }</pre><pre> ngOnInit() { <br> this.childName = ‘Boo’;<br> }<br> <br> isChildCrying(isIt: boolean) {<br> console.log(‘The child %s crying’, isIt ? ‘is’ : ‘is not’);<br> }<br>}</pre><p>Now every time the ChildComponent is hungry and emits the ‘cry’ event, the ParentComponentnow is able to listen for those events.</p><p>Of course we could create more methods to feed the ChildComponent and listen when it stops crying.</p><h3>Component Template Reference</h3><p>Another way to share information between ParentComponent and ChildComponent is by using a component reference and then access to properties or methods of that component.</p><pre>import {Component} from ‘@angular/core’;</pre><pre>@Component({<br> selector: ‘child-component’,<br> template: `I’m {{ name }}`<br>})</pre><pre>export class ChildComponent {</pre><pre> public name: string;<br> <br>}</pre><p>Now if we implement this ChildComponent within the ParentCompnent and get a reference, we will be able to get access to properties and methods from the parent template.</p><pre>import {Component, OnInit} from ‘@angular/core’;<br>import {ChildComponent} from ‘./child-component.ts’;</pre><pre>@Component({<br> selector: ‘parent-component’,<br> template: `<br>&lt;child-component #child&gt;&lt;/child-component&gt;<br>&lt;button (click)=”child.name = childName”&gt;&lt;/button&gt;<br>`,<br> directives: [ChildComponent]<br>})</pre><pre>export class ParentComponent implements OnInit {<br> <br> private childName: string;<br> <br> constructor() { }</pre><pre> ngOnInit() { <br> this.childName = ‘Boo’;<br> }<br>}</pre><h3>ChildView Injection</h3><p>I know this may sound scary, but the truth is that if you already understood the communication by<a href="http://mean.expert/2016/05/21/angular-2-component-communication/#Component_Template_Reference">Component Template References</a> then you may find that you may need to have access from theParentComponent and not from the parent component template.</p><pre>import {Component, AfterViewInit, ViewChild} from ‘@angular/core’;<br>import {ChildComponent} from ‘./child-component.ts’;</pre><pre>@Component({<br> selector: ‘parent-component’,<br> template: `&lt;child-component&gt;&lt;/child-component&gt;`,<br> directives: [ChildComponent]<br>})</pre><pre>export class ParentComponent implements AfterViewInit {<br> <br> @ViewChild(ChildComponent)<br> private cc: ChildComponent;<br> <br> constructor() { }</pre><pre> ngAfterViewInit() {<br> this.cc.name = ‘Boo’;<br> }<br>}</pre><p>Actually, I think this is a pretty neat way to communicate because is really clean, but I would use this method when the ChildComponent is part of a same module, otherwise I would choice between@Input @Outputor Services because you don’t really want to internally work/mess with 3rd party libraries.</p><h3>What is next?</h3><p>In my next blog posts I will bring some hot new topics by using <a href="http://horizon.io/">horizon.io</a> which just has been launched and of course I will talk about how to build a native realtime application using Angular 2and <a href="http://nativescript.org/">NativeScript 2</a>.</p><p>If you like this series and want be aware of next releases and new packages, follow me on Twitter<a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2adafd6fc52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a Container Component]]></title>
            <link>https://medium.com/@jcasarrubias/how-to-build-a-container-component-43d325d6091c?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/43d325d6091c</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Sat, 14 May 2016 16:08:16 GMT</pubDate>
            <atom:updated>2016-05-14T16:08:16.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*_YugJVaovtSSUCcV.jpg" /></figure><p>Angular 2: How To Build A Container Component.</p><p>Previously on <a href="http://mean.expert/2016/05/09/angular-2-future-now/">Angular 2: The Future of JavaScript is Now</a> I talked about all the cool features announced at the <a href="http://ng-conf.org/">#ngConf2016</a>. This time I have decided to start working in a new project in Angular 2 by using only the tools provided by the Angular 2 Ecosystem.</p><p>Each part of this project will help me to create more tutorials like this.</p><h3>Project Description</h3><p>I have been working with Angular 2 for 3 projects by now and something I have regullary seen is that we will need to create container components, basically everytime we build an application based on web components.</p><p>In this tutorial we are going to create an Angular 2 Container Component, this kind of components won’t render content but provides tools for developers to create different type of structures.</p><h3>Example of Implementation</h3><p>The container component we are going to create is going to help developers create grid structures, but if you have used <a href="http://ionic.io/">Ionic</a> or <a href="http://material.angular.io/">Angular Material</a> you should be familiar with these type of structures.</p><pre>&lt;grid&gt;<br> &lt;grid-title&gt;LATEST TUTORIALS&lt;/grid-title&gt;<br> &lt;grid-row&gt;<br> &lt;grid-item&gt;<br> &lt;/grid-item&gt;<br> &lt;/grid-row&gt;<br>&lt;/grid&gt;</pre><h3>Code Repo</h3><p><a href="https://github.com/jonathan-casarrubias/ng2-grid">NG2 Grid</a></p><h3>Requirements</h3><p>Install the <a href="http://cli.angular.io/">Angular CLI</a>.</p><pre>$ npm install -g angular-cli</pre><h3>Create Project</h3><p>Once we have the <a href="http://cli.angular.io/">Angular CLI</a> installed, we can create a new Angular 2 project namedcontainer.</p><pre>$ ng new container — prefix ‘’</pre><p>It will take some time until everything is installed, I added the — prefix ‘’ parameter because otherwise angular will append by default the app- prefix to any of our generated components.</p><p>For demo purposes it seems dirty if I leave the default prefix… But in real life, you will be adding your company or personal prefix as namespace of the component selector.</p><p>Then you can verify your app by running:</p><pre>$ cd container<br>$ ng serve</pre><p>If you open a browser and use the <a href="http://localhost:4200/">http://localhost:4200</a> path, you will be able to see a “Container Works!” message.</p><h3>Create Grid Component</h3><p>Now lets stop the server a moment and create our GridComponent using the <a href="http://cli.angular.io/">Angular CLI</a>‘s command ng generate</p><pre>$ ng generate component grid<br>Visit <a href="http://ember-cli.com/user-guide/#watchman">http://ember-cli.com/user-guide/#watchman</a> for more info.<br>installing component<br> create src/app/grid/grid.component.css<br> create src/app/grid/grid.component.html<br> create src/app/grid/grid.component.spec.ts<br> create src/app/grid/grid.component.ts<br> create src/app/grid/index.ts</pre><p>As you can see the generator created a set of files that composes our basic structure for the grid component.</p><h3>Define Grid Component View</h3><p>We won’t add logic to our component because this is a basic container component, of course we could add some logic if we want to take this component beyond, but that can be for a future blog post.</p><p>For now we are going to focus on create a view structure, for this we are going to use the&lt;ng-content&gt;&lt;/ng-content&gt; directive.</p><pre>&lt;ng-content select=”app-grid-title”&gt;&lt;/ng-content&gt;<br>&lt;ng-content&gt;&lt;/ng-content&gt;</pre><p>If you go back to the <a href="http://mean.expert/2016/05/14/angular-2-container-component/#Example_of_Implementation">Example of Implementation</a> you will see implemented the &lt;grid-title&gt;&lt;/grid-title&gt; selector, but we won’t actually create a directive or component for that, instead we use the select=”” within our &lt;ng-content&gt;&lt;/ng-content&gt; and we can actually select the content within that html tag and interpolate within our grid component view.</p><p>So whatever the developer who uses this directive passes as content will be interpolated within this component.</p><h3>Style Grid Component</h3><p>For this component we are going to use a lot the help of Flex the CSS3’s amazing functionallity that goes really well with this example, so we will build a good and more modern replacement for the native table html component.</p><pre>:host {<br> display: flex;<br> flex-direction: column;<br> border: 1px solid #eee;<br> border-right: 0px;<br>}</pre><pre>:host grid-title {<br> display: flex;<br> flex-direction: row;<br> padding: 15px 10px;<br> border-right: 1px solid #eee;<br>}</pre><p>When we use the selector :host we refer to the host component instance scope we are located, this is how we can provide some styling to the root container.</p><p>Then we set the flex direction to column because we want to create some sort of list in which we later will add rows in order to create a grid view.</p><h3>Generate Row and Item Components</h3><pre>$ ng generate component grid-row<br>$ ng generate component grid-item</pre><p>Now since we want to bundled our component together we need to move all filex exceptindex.ts the files created in src/app/grid-item and src/app/grid-row to thesrc/app/grid, at the end we should have a structure like the follow:</p><pre>+ src<br>| + app<br>| | + grid<br>| | | grid-item.component.css<br>| | | grid-item.component.html<br>| | | grid-item.component.ts<br>| | | grid-row.component.css<br>| | | grid-row.component.html<br>| | | grid-row.component.ts<br>| | | grid.component.css<br>| | | grid.component.html<br>| | | grid.component.ts<br>| | | index.ts</pre><p>Something really important when we are shipping multiple directives within our component is to export a directives array within our index.ts.</p><pre>import { GridComponent } from ‘./grid.component’;<br>import { GridRowComponent } from ‘./grid-row.component’;<br>import { GridItemComponent } from ‘./grid-item.component’;</pre><pre>export const GRID_DIRECTIVES = [<br> GridComponent,<br> GridRowComponent,<br> GridItemComponent<br>];</pre><p>You will see really ofen that you will be importing this form of components structure, so it makes life easier for the developers that will implement this code later on.</p><p>Important: since we created the row and item components using the generator, it configured for us the system-config.ts file in the app root, so we need to remove the following lines from the barrel section:</p><pre>const barrels: string[] = [<br> // Angular specific barrels.<br> ‘@angular/core’,<br> ‘@angular/common’,<br> ‘@angular/compiler’,<br> ‘@angular/http’,<br> ‘@angular/router’,<br> ‘@angular/platform-browser’,<br> ‘@angular/platform-browser-dynamic’,</pre><pre> // Thirdparty barrels.<br> ‘rxjs’,</pre><pre> // App specific barrels.<br> ‘app’,<br> ‘app/shared’,<br> ‘app/grid’,<br> ‘app/grid-row’, // ←- Remove This<br> ‘app/grid-item’, // ←- And Remove This<br> /** @cli-barrel */<br>];</pre><h3>Update Row and Item Views</h3><p>For both components we are going to use again the &lt;ng-content&gt;&lt;/ng-content&gt;directive without any other type of configurations, just the following:</p><p>Files: grid-row.component.html and grid-item.component.html</p><pre>&lt;ng-content&gt;&lt;/ng-content&gt;</pre><h3>Update Row and Item Styles</h3><p>File: grid-row.component.css</p><pre>:host {<br> display: flex;<br> flex: column;<br> flex-grow: 1;<br>}</pre><p>File: grid-item.component.css</p><pre>:host {<br> flex-grow: 1;<br> padding: 10px;<br> border: 1px solid #eee;<br> border-left: 0px;<br> border-bottom: 0px;<br>}</pre><h3>Implementation in ContainerAppComponent</h3><p>Open the container.component.ts file and update as follows:</p><pre>import { Component } from ‘@angular/core’;<br>import { GRID_DIRECTIVES } from ‘./grid’;</pre><pre>@Component({<br> moduleId: module.id,<br> selector: ‘container-app’,<br> templateUrl: ‘container.component.html’,<br> styleUrls: [‘container.component.css’],<br> directives: […GRID_DIRECTIVES]<br>})<br>export class ContainerAppComponent {<br> title = ‘container works!’;<br>}</pre><p>Remember the GRID_DIRECTIVES? well as you can see by implementing this in to the main component is much more easier than importing all of them and set each of these within the directives array section.</p><h3>Implementation in ContainerAppComponent View</h3><pre>&lt;h1&gt;<br> {{title}}<br>&lt;/h1&gt;<br>&lt;grid&gt;<br> &lt;grid-title&gt;Grid Title&lt;/grid-title&gt;<br>   &lt;grid-row&gt;<br>     &lt;grid-item&gt;<br>       A<br>     &lt;/grid-item&gt;<br>     &lt;grid-item&gt;<br>       B<br>     &lt;/grid-item&gt;<br>     &lt;grid-item&gt;<br>       C<br>     &lt;/grid-item&gt;<br>   &lt;/grid-row&gt;<br>   &lt;grid-row&gt;<br>     &lt;grid-item&gt;<br>       E<br>     &lt;/grid-item&gt;<br>     &lt;grid-item&gt;<br>       D<br>     &lt;/grid-item&gt;<br>   &lt;/grid-row&gt;<br>   &lt;grid-row&gt;<br>     &lt;grid-item&gt;<br>       F<br>     &lt;/grid-item&gt;<br>   &lt;/grid-row&gt;<br>&lt;/grid&gt;</pre><h3>Test</h3><p>Now if you start the server again by running</p><pre>$ ng serve</pre><p>You should be able to see a grid component with title, rows and items adjusted pretty neat because of the use of flex.</p><h3>What is next?</h3><p>In my next blog posts I will talk about component communications and I will be creating some tutorials for NodeJS Again.</p><p>If you like this series and want be aware of next releases and new packages, follow me on Twitter <a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43d325d6091c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 2: The Future of JavaScript is Now]]></title>
            <link>https://medium.com/@jcasarrubias/angular-2-the-future-of-javascript-is-now-eac09af3da43?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eac09af3da43</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[nativescript]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Sat, 07 May 2016 14:03:41 GMT</pubDate>
            <atom:updated>2016-05-07T14:04:52.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*g6nRX1vOuzR0Ha_M.png" /><figcaption>Angular 2: The Future of JavaScript is Now</figcaption></figure><p>You’ve probably heard about it. The <a href="http://angular.io/">Angular 2</a> Release Candidate 1 is out by now, aside the hype of the <a href="http://ng-conf.org/">#ngConf2016</a> and a bunch of exciting announcements from the Angular Team that literally made me throw a blog post scheduled for this week to the trash can and start again just to talk about farm fresh -not recently deprecated- news.</p><h3>About this Post</h3><p>In my previous blog posts I have been creating some tutorials and demo applications about the MEAN Stack.</p><p>This time I really want to focus and talk about all the cool new features announced at the<a href="http://ng-conf.org/">#ngConf2016</a>. Also I want to make this post a reference for the Angular 2 ecosystem which now goes beyond a simple web development framework.</p><p><em>Disclaimer: All of the following libraries are currently on development, api changes or issues may be found.</em></p><h3>Angular 2 Release Candidate</h3><p>Finally!!! after a couple of years, multiple conferences around the world and lots of hype:</p><p>The <a href="http://angular.io/">Angular 2</a> Framework is now on release candidate.</p><p>I have to be honest with you… Thanks to some changes they released on RC-0 now I need to update my blog posts (again) just to keep this valid for new people that wants to learn Angular 2, but yeah… that is the price of trying technologies on diapers.<br>The best way to install the release candidate 1 is to use the Angular CLI Tool.</p><h3>Angular CLI</h3><p>The first great tool from these guys I want to talk about is the Angular CLI which not only helps you to generate a scaffold of an Angular 2 Application, but it comes with with a set of commands to help developers, generate, serve, test and deploy.</p><p>One of the main complains I heard from the people I train on Angular, is that is difficult for them to understand where it starts and where it ends, we have been using Yeoman, Grunt, Gulp and all kind of tools to create a real development environment, now everything seems to be provided by the framework command line interface.</p><p><a href="http://cli.angular.io/">Angular CLI</a></p><h3>Angular Universal</h3><p>Anothere great feature that has been buzzing around for a while and now is a reallity: Server-side Rendering for Angular 2 apps. How many of you have had the Angular 1 SEO Nightmare?</p><p>As they states in their site, finally we will be able to get site previews, optimized search engines and a much more improved performance</p><p><a href="https://universal.angular.io/">Angular Universal</a></p><h3>Angular Mobile Tool Kit</h3><p>Angular Mobile Tool Kit? did’t you see that coming huh? but yes they are also providing a mobile toolkit to create installable, offline-capable, mobile-network-friendly Angular 2 Apps right away.</p><p><a href="https://mobile.angular.io/">Angular Mobile ToolKit</a></p><h3>Angular Augury</h3><p>In my experience working with Angular 2. I found that debugging was really hard, there were a lot of unreadable traces, so another amazing surprise for me was the announcement of the Angular Augury Tool, which is chrome plugin to debbug NG2 Apps in a really cool way, it actually manage the component tree in a graphic representation which is pretty cool.</p><p><a href="https://augury.angular.io/">Angular Augury</a></p><h3>Angular Material 2</h3><p>I bet most of you that already know Angular 1 may be involved with Angular Material, which is an NG Implementation of the Material Design Spec.</p><p>Well there is a team of Google Developers working along the community on the second version for the Angular Material 2 components, but this time looks like they are looking to go beyond creating more powerful components than before.</p><p>This is in its really early stages, so if you like to contribute here is the repo:</p><p><a href="https://github.com/angular/material2">Angular Material 2</a></p><h3>Angular Firebase 2</h3><p>One more super cool announced tool is the Angular Firebase 2, you literally can build a chat for no more than 200 lines of code, I really think the modern web development is designed for realtime applications and the Angular Firebase 2 is an example of it.</p><p><a href="https://github.com/angular/angularfire2">Angular Firebase 2</a></p><h3>Angular 2 Style Guide</h3><p>For me something super awesome and unexpected is that the Angular Team presented:</p><p><a href="http://angular.io/styleguide">Angular 2 Style Guide</a></p><p>As a software architect I appreciate the fact that these guys published a pretty good documentation to help any developer maintain concistency while using this framework to develop web, desktop or mobile apps.</p><h3>Angular References</h3><p>Until now, Angular 2 references were really difficult to find, fortunately the team also provided a section in which everyone can find information and resources about the Angular 2 tools and tutorials.</p><p><a href="http://angular.io/references">Angular References</a></p><h3>Angular Contributions</h3><p>If you want to be part of the community and contribute you can do it by accessing the ng-contrib page and register.</p><p><a href="https://ng-contrib.org/">Angular Contributions</a></p><h3>Native Script 2.0</h3><p>Wait, what?… Yes There also was an announcement of the Native Script 2.0 with full support of the Angular 2 framework, but what does this mean? well finally we will be able to write Native Applications using Angular 2 without rendering dom in a web view!! pretty cool huh?</p><p><a href="https://www.nativescript.org/">Native Script 2.0</a></p><h3>Codelyzer</h3><p>Is a code analyzer for Angular 2 Applications that lints your code and verify if the architecture is even following the <a href="http://angular.io/styleguide">Angular 2 Style Guide</a>.</p><p><a href="https://github.com/mgechev/codelyzer">Codelyzer</a></p><h3>Thoughts</h3><p>Working with Angular 2 for the last 6 months has been really amazing aside of the fact they have changed the packages names and some syntax during this time, I have been buying and enjoying this concept for a while… Since alpa version and I see comments everywere asking if Angular 2 is ready for developing real applications and I would answer, Yes.. Actually I don’t see the moment we finish with legacy systems in Angular 1, but yeah I know this is a transitacional moment and the best is about to come.</p><p>As you can see during the <a href="http://ng-conf.org/">#ngConf2016</a> there was a good amount of announcements, I know many of this technologies are in development but what I can think is in a modern web development accross the road.</p><h3>What is next?</h3><p>In my next blog posts I’m going to start digging into the listed technologies.</p><p>If you like this blog and want be aware of next releases and new packages, follow me on Twitter <a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eac09af3da43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build A Chart Component in Angular 2 and D3]]></title>
            <link>https://medium.com/@jcasarrubias/how-to-build-a-chart-component-in-angular-2-and-d3-c0a15d845eca?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0a15d845eca</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Fri, 06 May 2016 14:10:43 GMT</pubDate>
            <atom:updated>2016-05-06T14:11:08.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*6eq4dha92UK_V4OU.jpg" /></figure><p>Previously on <a href="http://mean.expert/2016/04/25/angular-2-and-loopback/">Building Easy Stats with Angular 2, D3 and LoopBack</a> I explained how to integrate Angular 2 with StrongLoop’s <a href="https://loopback.io/">LoopBack</a> Framework by using the Http Library and Observables. This time we will focus on creating an Area Chart Component in Angular 2 and<a href="https://d3js.org/">D3</a> to represent our Customer Orders.</p><h3>Project Description</h3><p>In this tutorial we are going to create an Angular 2 Chart Component implementing the datasets we got in my <a href="http://mean.expert/2016/04/25/angular-2-and-loopback/">last post</a> with the help of the <a href="https://d3js.org/">D3</a> Library.</p><p>I know in a near future there would be amazing NG2 Chart Components to get from NPM, but in this project I’m trying to achieve 2 things:</p><ul><li>Show you how to create your own Angular 2 Components.</li><li>Show you how to create your D3 Charts.</li></ul><p>This will help you in the future to deliver much more customized charts to your customers and/or software products.</p><p>Later on, in my next blog post we will be using <a href="https://github.com/angular/material2">Angular Material 2</a> to create a nice user interface to help us create customers, take orders and see how the charts are updated in real time.</p><h3>Demo App</h3><p>By the moment you finish this tutorial, you should be able to render an area chart built in Angular 2 and D3, even though we won’t have the user interface just jet, it is time for me to deploy a demo app:</p><p><a href="http://stats.mean.expert/">Click Here For Demo APP</a></p><h3>Project Index</h3><ul><li><a href="http://mean.expert/2016/04/13/loopback-stats-mixin">API Setup</a>.</li><li><a href="http://mean.expert/2016/04/21/loopback-stats-mixin-part2">STATS Endpoints</a>.</li><li><a href="http://mean.expert/2016/04/25/angular-2-and-loopback/">Angular 2 App Setup</a>.</li><li>Build an NG2 Chart Component.</li><li>Create Angular Material 2 Interface.</li></ul><h3>Install D3 and Moment</h3><p>After you verified the app installed and ran correctly, kill the process and install d3.</p><pre>$ npm install d3 moment — save<br>$ typings install d3 moment — save</pre><h3>Create Chart Component Files</h3><pre>+ charts<br>|- area-chart.css<br>|- area-chart.ts<br>|- area-chart-config.ts<br>|- index.ts</pre><h3>Create Area Chart Component</h3><p>First we need to create an AreaChart Component so lets create the basic structure:</p><p>File: charts/area-chart.ts</p><pre>import {Component} from ‘angular2/core’;</pre><pre>@Component({<br> selector: ‘area-chart’,<br> template: `&lt;ng-content&gt;&lt;/ng-content&gt;`,<br> styleUrls: [‘app/components/charts/area-chart.css’],<br> directives: []<br>})</pre><pre>export class AreaChart {</pre><pre> private host; // D3 object referebcing host dom object<br> private svg; // SVG in which we will print our chart<br> private margin; // Space between the svg borders and the actual chart graphic<br> private width; // Component width<br> private height; // Component height<br> private xScale; // D3 scale in X<br> private yScale; // D3 scale in Y<br> private xAxis; // D3 X Axis<br> private yAxis; // D3 Y Axis<br> private htmlElement; // Host HTMLElement</pre><pre> /* Constructor, needed to get @Injectables */<br> constructor(): void {}<br> <br> /* Will Update on every @Input change */<br> ngOnChanges(): void {}<br> <br> /* Will setup the chart container */<br> private setup(): void {}<br> <br> /* Will build the SVG Element */<br> private buildSVG(): void {}<br> <br> /* Will draw the X Axis */<br> private drawXAxis(): void {}<br> <br> /* Will draw the Y Axis */<br> private drawYAxis(): void {}<br> <br> /* Will get the Maximum value in Y */<br> private getMaxY(): number {}</pre><pre> /* Will populate datasets into areas*/<br> private populate(): void {}<br>}</pre><p>This is going to be our Component structure and for obvious it may seems I added some comments to explain every part of the component Class.</p><h3>Create AreaChartConfig</h3><p>Since we will require a configuration object to be set from the parent component and we decided to use TypeScript I decided to create the AreaChartConfig so we receive the specific needed configuration.</p><p>File: charts/area-chart.ts</p><pre>export class AreaChartConfig { <br> settings: { fill: string, interpolation: string };<br> dataset: Array&lt;{ x: string, y: number }&gt;<br>}</pre><p>Great now we have set the rules of how the configuration should be passed to our AreaChart Component.</p><h3>Add @Input config</h3><p>Ok, we already set the rules of what the config structure should looks like, but now we need to say our AreaChart Component to receive this type of configuration, that can be done with the use of the @Input decorator.</p><p>File: charts/area-chart.ts</p><pre>@Input() config: Array&lt;AreaChartConfig&gt;;</pre><p>Of course if we are using Visual Studio Code, or any IDE with TypeScript support will complain of the missing dependency AreaChartConfig, so lets configure that.</p><h3>Import AreaChart Component Dependencies</h3><p>File: charts/area-chart.ts</p><pre>import {AreaChartConfig} from ‘./area-chart-config’;<br>import * as D3 from ‘d3/index’;<br>import * as Moment from ‘moment’;</pre><h3>Add Methods Logic</h3><p>Now We can add the logic of our AreaChart Component:<br>File: charts/area-chart.ts</p><pre>import {Component, Input, ElementRef} from ‘angular2/core’;<br>import {AreaChartConfig} from ‘./area-chart-config’;<br>import * as D3 from ‘d3/index’;<br>import * as Moment from ‘moment’;</pre><pre>@Component({<br> selector: ‘area-chart’,<br> template: `&lt;ng-content&gt;&lt;/ng-content&gt;`,<br> styleUrls: [‘app/components/charts/area-chart.css’],<br> directives: []<br>})</pre><pre>export class AreaChart {</pre><pre> @Input() config: Array&lt;AreaChartConfig&gt;;</pre><pre> private host;<br> private svg;<br> private margin;<br> private width;<br> private height;<br> private xScale;<br> private yScale;<br> private xAxis;<br> private yAxis;<br> private htmlElement: HTMLElement;<br> /**<br> * We request angular for the element reference <br> * and then we create a D3 Wrapper for our host element<br> **/<br> constructor(private element: ElementRef) {<br> this.htmlElement = this.element.nativeElement;<br> this.host = D3.select(this.element.nativeElement);<br> }<br> /**<br> * Everythime the @Input is updated, we rebuild the chart<br> **/<br> ngOnChanges(): void {<br> if (!this.config || this.config.length === 0) return;<br> this.setup();<br> this.buildSVG();<br> this.populate();<br> this.drawXAxis();<br> this.drawYAxis();<br> }<br> /**<br> * Basically we get the dom element size and build the container configs<br> * also we create the xScale and yScale ranges depending on calculations<br> **/<br> private setup(): void {<br> this.margin = { top: 20, right: 20, bottom: 40, left: 40 };<br> this.width = this.htmlElement.clientWidth — this.margin.left — this.margin.right;<br> this.height = this.width * 0.5 — this.margin.top — this.margin.bottom;<br> this.xScale = D3.time.scale().range([0, this.width]);<br> this.yScale = D3.scale.linear().range([this.height, 0]);<br> }<br> /**<br> * We can now build our SVG element using the configurations we created<br> **/<br> private buildSVG(): void {<br> this.host.html(‘’);<br> this.svg = this.host.append(‘svg’)<br> .attr(‘width’, this.width + this.margin.left + this.margin.right)<br> .attr(‘height’, this.height + this.margin.top + this.margin.bottom)<br> .append(‘g’)<br> .attr(‘transform’, ‘translate(‘ + this.margin.left + ‘,’ + this.margin.top + ‘)’);<br> }<br> /**<br> * Method to create the X Axis, will use Month as tick date format<br> * Also assing some classes for CSS Stylimg<br> **/<br> private drawXAxis(): void {<br> this.xAxis = D3.svg.axis().scale(this.xScale)<br> .tickFormat(t =&gt; Moment(t).format(‘MMM’).toUpperCase())<br> .tickPadding(15);<br> this.svg.append(‘g’)<br> .attr(‘class’, ‘x axis’)<br> .attr(‘transform’, ‘translate(0,’ + this.height + ‘)’)<br> .call(this.xAxis);<br> }<br> /**<br> * Method to create the Y Axis, will use numeric values as tick date format<br> * Also assing some classes for CSS Stylimg and rotating the axis vertically<br> **/<br> private drawYAxis(): void {<br> this.yAxis = D3.svg.axis().scale(this.yScale)<br> .orient(‘left’)<br> .tickPadding(10);<br> this.svg.append(‘g’)<br> .attr(‘class’, ‘y axis’)<br> .call(this.yAxis)<br> .append(‘text’)<br> .attr(‘transform’, ‘rotate(-90)’);<br> }<br> /**<br> * Will return the maximum value in any dataset inserted, so we use<br> * it later for the maximum number in the Y Axis<br> **/<br> private getMaxY(): number {<br> let maxValuesOfAreas = [];<br> this.config.forEach(data =&gt; maxValuesOfAreas.push(Math.max.apply(Math, data.dataset.map(d =&gt; d.y))));<br> return Math.max(…maxValuesOfAreas);<br> }<br> /**<br> * Now we populate using our dataset, mapping the x and y values<br> * into the x and y domains, also we set the interpolation so we decide<br> * how the Area Chart is plotted.<br> **/<br> private populate(): void {<br> this.config.forEach((area: any) =&gt; {<br> this.xScale.domain(D3.extent(area.dataset, (d: any) =&gt; d.x));<br> this.yScale.domain([0, this.getMaxY()]);<br> this.svg.append(‘path’)<br> .datum(area.dataset)<br> .attr(‘class’, ‘area’)<br> .style(‘fill’, area.settings.fill)<br> .attr(‘d’, D3.svg.area()<br> .x((d: any) =&gt; this.xScale(d.x))<br> .y0(this.height)<br> .y1((d: any) =&gt; this.yScale(d.y))<br> .interpolate(area.settings.interpolation));<br> });<br> }<br>}</pre><h3>Add Basic Styling</h3><p>File: charts/area-chart.css</p><pre>:host {<br> width: 100%;<br> display:block;<br>}<br>:host .axis path,<br>:host .axis line {<br> fill: none;<br> stroke: rgba(0, 0, 0, 0.2);<br> color: rgba(0, 0, 0, 0.2);<br> shape-rendering: crispEdges;<br>}</pre><pre>:host .axis text {<br> font-size: 11px;<br> fill: rgba(0, 0, 0, 0.9);<br>}</pre><pre>:host .grid .tick {<br> stroke: rgba(0, 0, 0, 0.1);<br> opacity: 0.3;<br>}</pre><pre>:host .grid path {<br> stroke-width: 0;<br>}</pre><pre>:host .grid .tick {<br> stroke: rgba(0, 0, 0, 0.1);<br> opacity: 0.3;<br>}</pre><pre>:host .grid path {<br> stroke-width: 0;<br>}<br>:host .color-label{<br> display: inline;<br>}</pre><h3>Update Stats Component</h3><p>In <a href="http://mean.expert/2016/04/25/angular-2-and-loopback/">my last post</a> I explained how to get the data and we actually proved by doing a console log of the result, but now is time to connect our Stats Component with our Area Chart Component.</p><pre>import {Component} from ‘angular2/core’;<br>import {StatsService} from ‘./stats.service’;<br>import {AreaChart, AreaChartConfig} from ‘../charts’;</pre><pre>@Component({<br> selector: ‘stats’,<br> templateUrl: ‘app/components/stats/stats.html’,<br> styleUrls: [‘app/components/stats/stats.css’],<br> providers: [StatsService],<br> directives: [AreaChart],<br> pipes: []<br>})</pre><pre>export class Stats {</pre><pre> private areaChartConfig: Array&lt;AreaChartConfig&gt;;</pre><pre> constructor(private statsService: StatsService) { this.getStats(); }</pre><pre> getStats() {<br> // For now we hardcode the customer Id until we build a user interface.<br> this.statsService.byCustomer(1, ‘monthly’).subscribe(stats =&gt; {<br> // Get JSON Object from Response<br> stats = stats.json();<br> <br> // We create a new AreaChartConfig object to set income by customer config<br> let customerIncomeArea = new AreaChartConfig();<br> customerIncomeArea.settings = {<br> fill: ‘rgba(1, 67, 163, 1)’,<br> interpolation: ‘monotone’<br> };<br> customerIncomeArea.dataset = stats.customerIncomeStats.map(data =&gt; {<br> return { x: new Date(data.date), y: data.count };<br> });<br> <br> // We create a new AreaChartConfig object to set orders by customer config<br> let customerOrderArea = new AreaChartConfig();<br> customerOrderArea.settings = {<br> fill: ‘rgba(195, 0, 47, 1)’,<br> interpolation: ‘monotone’<br> };<br> customerOrderArea.dataset = stats.customerOrderStats.map(data =&gt; {<br> return { x: new Date(data.date), y: data.count };<br> });<br> <br> // to finish we append our AreaChartConfigs into an array of configs <br> this.areaChartConfig = new Array&lt;AreaChartConfig&gt;();<br> this.areaChartConfig.push(customerIncomeArea);<br> this.areaChartConfig.push(customerOrderArea);<br> });<br> }<br>}</pre><h3>Update Stats View</h3><p>Now we pass a config object that contains a number of AreaChartConfigs</p><pre>&lt;h1&gt;Angular 2 Chart Component&lt;/h1&gt;<br>&lt;area-chart *ngIf=”areaChartConfig” [config]=”areaChartConfig”&gt;&lt;/area-chart&gt;</pre><h3>Test</h3><p>If you start both, the front end/ back end servers again $ npm start and $ slc run you will be able to see the AreaChart component in the browser..</p><p>Also: <a href="http://stats.mean.expert/">Click Here For Demo APP</a></p><h3>What is next?</h3><p>In my next blog posts we are going to create a user interface using <a href="https://github.com/angular/material2">Angular Material 2</a> in order to make this project more interesting, so we can create new customers, take orders and see how the chart is updated.</p><p>If you like this series and want be aware of next releases and new packages, follow me on Twitter <a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0a15d845eca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Easy Stats with Angular 2, D3 and LoopBack]]></title>
            <link>https://medium.com/@jcasarrubias/building-easy-stats-with-angular-2-d3-and-loopback-c55bddf10b9d?source=rss-4298d94ff69b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c55bddf10b9d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Jonathan Casarrubias]]></dc:creator>
            <pubDate>Wed, 27 Apr 2016 16:02:51 GMT</pubDate>
            <atom:updated>2016-04-27T16:02:51.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*ac046iciVmwIK7cA.jpg" /></figure><p>Building Easy Stats with Angular 2, D3 and LoopBack.</p><p>Previously on <a href="http://mean.expert/2016/04/21/loopback-stats-mixin-part2">How to build Easy Stats with LoopBack — Part 2</a> I explained how to make a more advanced use of the <a href="https://www.npmjs.com/package/loopback-stats-mixin">loopback-stats-mixin</a>. Now we want to have some fun and represent that datasets into some good looking charts made on Angular 2 and <a href="https://d3js.org/">D3</a>.</p><h3>Project Description</h3><p>In this tutorial we are going to create an Angular 2 App using the <a href="https://github.com/angular/angular2-seed">Angular 2 Seed</a>, making a StatsComponent that will get the datasets resulting from the API we built in <a href="http://mean.expert/2016/04/13/loopback-stats-mixin">Part 1</a> and <a href="http://mean.expert/2016/04/21/loopback-stats-mixin-part2">Part 2</a>.</p><p>Later on, we will be using <a href="https://d3js.org/">D3</a> to create a chart component that will help us to represent the data we created in my previous posts.</p><h3>Requirements</h3><ul><li>Node JS</li><li>NPM</li><li>TypeScript</li><li>GitHub</li><li>Follow <a href="http://mean.expert/2016/04/13/loopback-stats-mixin">Part 1</a> and <a href="http://mean.expert/2016/04/21/loopback-stats-mixin-part2">Part 2</a> if you care about how we got the datasets for the charts.</li></ul><h3>Setup Angular Project</h3><p>For this project we are going to use the <a href="https://github.com/angular/angular2-seed">Angular 2 Seed</a> from Angular’s GitHub Account.</p><p>$ git clone <a href="https://github.com/angular/angular2-seed">https://github.com/angular/angular2-seed</a><br>$ mv angular2-seed easy-stats/client<br>$ cd easy-stats/client<br>$ npm install -g webpack webpack-dev-server typings typescript<br>$ npm install</p><p>Since the default API Port is 3000 as well as the Angular 2 Seed, we need to modify one of these, in this case I will update the package.json from the NG2 App to serve in port 3030.</p><pre>{<br>“server”: “node node_modules/webpack-dev-server/bin/webpack-dev-server.js — inline — colors — progress — display-error-details — display-cached — port 3030 — content-base src”,<br>}</pre><p>Now you can start the <a href="http://angular.io/">Angular 2</a> App by running the following command within the easy-stats/client directory.</p><pre>$ npm start</pre><p>To verify that the seed was correctly installed and started open your browser in the following route<a href="http://localhost:3030/">http://localhost:3030/</a></p><p>This tutorial is based in version 2.0.0-beta.15 but I will try to keep it valid after first stable version is released.</p><h3>Install D3</h3><p>After you verified the app installed and ran correctly, kill the process and install d3.</p><pre>$ npm install d3 — save<br>$ typings install d3 — save</pre><h3>Fun Time</h3><p>Ok I won’t go in details about the basic structure of an <a href="http://angular.io/">Angular 2</a> Application since there are a good amount of published blogs that talks about the basics, what I want to do is to have some fun and go beyond.</p><p>So… if you feel you need to understand the basics I recommend you to read the <a href="https://angular.io/docs/ts/latest/quickstart.html">Angular’s Official Getting Started</a> then you can come back here and continue the tutorial.</p><h3>Create Stats Files</h3><pre>$ mkdir easy-stats/client/src/app/components/stats</pre><p>Now create stats.ts, stats.service.ts, stats.html and stats.css files within that directory</p><p>+ stats<br>|- stats.ts<br>|- stats.service.ts<br>|- stats.html<br>|- stats.css</p><h3>Create Stats Service</h3><p>In order to communicate our NG2 App with our LB API, we need to create an injectable service that will later use as provider in our Stats Component.</p><p>File: src/app/components/stats/stats.service.ts</p><pre>import {Injectable} from ‘angular2/core’;<br>import {Http} from ‘angular2/http’;<br>import {Observable} from ‘rxjs/Observable’;</pre><pre>@Injectable()<br>export class StatsService {<br> <br> private url: string = ‘http://localhost:3000/api&#39;;</pre><pre>constructor(private http: Http) { }<br> <br> byCustomer(id: any, range: string): Observable&lt;any&gt; {<br> return this.http.get(this.url + ‘/customers/’ + id +’/stats?range=’ + range);<br> }<br>}</pre><p>Since created some endpoints to get statistical information regarding specific customers then we need to create a method within our service that will help us to gather that information.</p><p>Seems simple huh? well for those who does not know, we addressed a grouping behavior in order to make just 1 call to fetch every statistical information in 1 API Request.</p><p>If you are not aware of how to create the API to serve this information and now you are interested, see <a href="http://mean.expert/2016/04/13/loopback-stats-mixin">Part 1</a> and <a href="http://mean.expert/2016/04/21/loopback-stats-mixin-part2">Part 2</a>.</p><p>Now we can inject the StatsService into our stats component we about to create.</p><h3>Create Stats Component</h3><p>We need to create a component that will get the datasets from our LoopBack application, for this we need to import the StatsService and include it as provider.</p><pre>import {Component} from ‘angular2/core’;<br>import {StatsService} from ‘./stats.service’;</pre><pre>@Component({<br> selector: ‘stats’,<br> templateUrl: ‘app/components/stats/stats.html’,<br> styleUrls: [‘app/components/stats/stats.css’],<br> providers: [StatsService],<br> directives: [],<br> pipes: []<br>})</pre><pre>export class Stats {</pre><pre>private customerId: any;<br> private range: string = ‘weekly’;</pre><pre>constructor(private statsService: StatsService) { }</pre><pre>ngOnInit() {<br> }</pre><pre>getStats() {<br> this.statsService.byCustomer(this.customerId, this.range)<br> .subscribe(stats =&gt; console.log(stats.json()));<br> }<br>}</pre><p>The customerId and range properties will help us to create a small form that will help us to get specific statistics in range but also from customer Ids.</p><p>I will leave the customerId type as any, since can be numeric sql environments or string when using mongodb.</p><p>I created the getStats method so we can bind it to a button in our view, this method will subscribe to the Observable we got from the StatsService.byCustomer method.</p><p>For now, we are just doing a console log to verify we are getting the data from our API, the next step will be to connect with a D3 Chart Component we are going to create.</p><h3>Adding the View</h3><p>Modify the stats.html file adding the following markup:</p><pre>&lt;h1&gt;Easy Stats&lt;/h1&gt;<br>&lt;label for=”customerId”&gt;Customer Id:&lt;/label&gt;<br>&lt;input name=”customerId” type=”text” [(ngModel)]=”customerId” placeholder=”customerId” /&gt;<br>&lt;label for=”range”&gt;Range:&lt;/label&gt;<br>&lt;input name=”range” type=”text” [(ngModel)]=”range” placeholder=”range” /&gt;<br>&lt;button (click)=”getStats()”&gt;Get Stats&lt;/button&gt;</pre><h3>Update seed-app.ts</h3><p>Now we need to say the angular app to use our Stats Component by configuring the seed-app.ts file as follows:</p><pre>import {Component} from ‘angular2/core’;<br>import {Router, RouteConfig, ROUTER_DIRECTIVES} from ‘angular2/router’;<br>import {Stats} from ‘./components/stats/stats’;</pre><pre>@Component({<br> selector: ‘seed-app’,<br> providers: [],<br> pipes: [],<br> directives: [ROUTER_DIRECTIVES],<br> templateUrl: ‘app/seed-app.html’,<br>})</pre><pre>@RouteConfig([<br> { path: ‘/’, component: Stats, name: ‘Stats’, useAsDefault: true }<br>])</pre><pre>export class SeedApp {<br> constructor() {}<br>}</pre><p>Also I wanted to clean the app by removing the built in components and leaving only the Stats component ponted to the root path.</p><h3>Before Test</h3><p>Before testing the app you need to make sure your API is running and you have set a number of customers and orders.</p><p>Also, we did not setup any datasource to our API, if you stop the process you will lose your data, therefore you won’t be able to test this app.</p><p>To avoid that behaviour you will need to <a href="https://docs.strongloop.com/display/public/LB/datasources.json">Setup a DataSource in LoopBack</a>.</p><h3>Test</h3><p>If you start the server again $ npm start you will be able to see a form that will help you get the information from the API we built.</p><p>For now, we are able to verify the information on the Browser’s Console.</p><h3>What is next?</h3><p>In my next blog posts we are going to create our <a href="https://d3js.org/">D3</a> Chart Component in <a href="http://angular.io/">Angular 2</a>, also give some styling to the page by either using <a href="https://github.com/angular/material2">Angular Material 2</a> or <a href="http://v4-alpha.getbootstrap.com/">Bootstrap 4</a>.</p><p>If you want to help decide between <a href="https://github.com/angular/material2">Angular Material 2</a> or <a href="http://v4-alpha.getbootstrap.com/">Bootstrap 4</a>, leave a comment and we will decide together.</p><p>If you like this series and want be aware of next releases and new packages, follow me on Twitter<a href="https://twitter.com/johncasarrubias">@johncasarrubias</a> and if you feel it leave a comment here.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c55bddf10b9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>