12/29/16

Unit Tests With Typescript

Hi lovely people my-gs500-blog-readers! I'm so glad to meet you again!
Today i want to speak about unit tests. Yes, a already wrote some series about unit testing angular1 directives, but now it is slightly different.
Why? Because i'm talking about angular typescript project.
Remember this angular-seed repo, we learned how to translate it to typescript(in this post)?
So, since the project is now contains only typescript (.ts) files - current tests would not work anymore (Because all the code that tests should be testing is not exists yet, it need to be transpilled to javascript)

Translate The Tests To Typescript

First thing to start with - lets translate all the tests to typescript: This is very simple, instead of:


'use strict';

describe('myApp.version module', function() {
  beforeEach(module('myApp.version'));

  describe('version service', function() {
    it('should return current version', inject(function(version) {
      expect(version).toEqual('0.1');
    }));
  });
});


now it is:

import * as angular from "angular";
import "angular-mocks";
import "phantomjs-polyfill";
import {version} from './version'
describe('myApp.version module', () => {
  beforeEach(angular.mock.module('myApp.version'));

  describe('version service', () => {
    it('should return current version', () => {
      expect(version).toEqual('0.1');
    });
  });
});

Not a big difference, right?

Karma Is A Bitch

Next things we need to change karma.conf file, to explain to karma: "you should load ts files now, baby"


...
files: [
    './node_modules/phantomjs-polyfill/bind-polyfill.js',
    './app/test.ts'
]
...


Processing With Webpack

For convert ts files to ES5 you need to use some transpiling tool, for example webpack:


    ...
    plugins: [
      require('karma-webpack'),
      require('karma-sourcemap-loader'),
      require('karma-jasmine'),
      require('karma-phantomjs-launcher'),
      require('karma-chrome-launcher')
    ],

    webpack: webpackConfig,
    webpackMiddleware: {
      stats: { chunks: false },
    },


    ...

For full code look in this repo

12/25/16

Add Ajax Request Indicator

Some times it is good practice to notify user that due to his actions (like sending the contact us form) some ajax request been sent and it is been processed. If you not reckon with nprogress angular lib yet, this good opportunity to introduce it... This library is angular implementation of nprogress jquery plugin, and its showing very nice loading bar on top of you application:

How to make it shown only if some ajax request made?

If you don't want to track any other requests like js and css files, only data requests to backend, it may be done by watching pendingRequests property of $http angular service:


myApp.run(function ($rootScope, $http, ngProgressFactory) {
        $rootScope.progrs = ngProgressFactory.createInstance();
        var progresstarted, progressbar = $rootScope.progrs;
        $rootScope.$watch(function() {
            var onlyJsonRequests = $http.pendingRequests.filter(function(r){return r.url.match(/json/g);});
            return onlyJsonRequests.length;
        }, function(n) {
             
            if(n>0 && !progresstarted) {
             
                progresstarted = true; 
                progressbar.setColor('blue');
                progressbar.setParent(document.getElementById('mainContainer')); //set a custom container, otherwise will be attached to "body"
               
                progressbar.start();
            } else if(n===0 && progresstarted) { 
                progressbar.complete(); 
                progresstarted = false;  
            }
        }) 
}) 

Notice that progress bar will be shown only if requests with url property that contains /json/ are sent

Provider is Better

Currently we have a lot of logic inside our run section.
One thing that can make the code more accurate is to move the progress logic to provider recipy:


myApp.provider('progress', function($provide, $injector) {
  this.setPattern = function(pattern) {
    this.pattern = new RegExp(pattern,'g');
  };
  this.setContainer = function(container) {
    this.container = container;
  };
  this.setColor = function(color) {
    this.color = color;
  };
  //will fire when used in one of recipies like "controller" or "directive" or "run"
  this.$get = function ($rootScope, $http, ngProgressFactory) {
        var that = this;
        $rootScope.progrs = ngProgressFactory.createInstance();
        var progresstarted, progressbar = $rootScope.progrs;
        $rootScope.$watch(function() {
            var onlyJsonRequests = $http.pendingRequests.filter(function(r){
              return r.url.match(that.pattern);
            });
            return onlyJsonRequests.length;
        }, function(n) {
            if(n>0 && !progresstarted) {
                progresstarted = true; 
                progressbar.setColor(that.color);
               progressbar.setParent(document.getElementById(that.container)); 
                progressbar.start();
            } else if(n===0 && progresstarted) { 
                progressbar.complete(); 
                progresstarted = false;  
            }
        }) 
        return 'watching'
   };
});

Now we can set all the custom settings inside config section:

myApp.config(function(progressProvider) {
  progressProvider.setContainer('mainContainer');
  progressProvider.setPattern('json');
  progressProvider.setColor('blue');

Now inside our run section we can leave only progress injection:

myApp.run(function (progress) {
}) 

If you want to see the full code - look on this plnkr

12/14/16

Creating Material Chips Input For Angular2

What Are Those Chips I'm Talking About

Here are some of many implementations that can be found across the web:
materializecss
angularjs material
Look at this gif that demonstrates chips behavior:

Angular2 Chips

Recently I looked on Angular Material2 repository that being developed quickly those days. I noticed that currently the chips ui is not developed yet, So i decided to try to do it myself and here i want to share some of my thoughts about this challenge of mine...

References Of Experts

During my research i was helped reading by those great articles of those 3 great guys: implementing-angular2-forms-beyond-basics
linkup-custom-control-to-ngcontrol-ngmodel
understanding-controlvalueaccessor

First Way

We may make some component that gets chips array as two way binding parameter from its parent
HTML:


   //in parent component:
   values:string[]=['lolo']
    ...
   <chips [chips]="values"></chips>

chipsComponent.ts:

import {Component, Input, Output, EventEmitter} from '@angular/core'
@Component({
  selector: 'chips',
  template: `
   <div *ngIf="values">
      <span *ngFor="let value of values" style="font-size:14px"
          class="label label-default" (click)="removeValue(tag)">
        {{value}} <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
      </span>
      <span> | </span>
      <span style="display:inline-block;">
        <input [(ngModel)]="labelToAdd" style="width: 50px; font-size: 14px;" class="custom"/>
        <em class="glyphicon glyphicon-plus" aria-hidden="true" (click)="addValue(valueToAdd)"></em>
      </span>
    </div>
  `
})
export class Chips { 
  @Input()
  get chips() {
    return this.values;
  }
  set chips(val) {
    this.values = val;
    this.labelsChange.emit(this.values);
  }

  @Output()
  labelsChange: EventEmitter = new EventEmitter();

  removeValue(value:string) {
    var index = this.values.indexOf(value, 0);
    if (index != undefined) {
      this.values.splice(index, 1);
      this.labelsChange.emit(this.values);
    }
  }

  addValue(value:string) {
    this.values.push(this.labelToAdd);
    this.labelsChange.emit(this.values);
    this.labelToAdd = '';
  }
}

see this code runs in plunker

Second Way (using Angular2 Forms)

My goal was to create a component/driective that will use ngModel directive to update the model:



 <material-chips [(ngModel)]="tags" ></material-chips>


For this we need to implement valueAccessor interface:

import {Component, NgModel, NgModule, OnInit, Input, Output, EventEmitter, ElementRef, forwardRef} from '@angular/core'

import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';


const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => Chips),
    multi: true
};

@Component({
  selector: 'chips',
  template: `
    <div *ngIf="values">
      <span *ngFor="let value of values" style="font-size:14px"
          class="label label-default" (click)="removeValue(tag)">
        {{value}} <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
      </span>
      <span> | </span>
      <span style="display:inline-block;">
        <input [(ngModel)]="labelToAdd" style="width: 50px; font-size: 14px;" class="custom"/>
        <em class="glyphicon glyphicon-plus" aria-hidden="true" (click)="addValue(valueToAdd)"></em>
      </span>
    </div>
  `,
   providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] 
})
export class Chips  implements ControlValueAccessor { 
  //by the Control Value Accessor
  private onTouchedCallback: () => void = noop;
  private onChangeCallback: (_: any) => void = noop;
  registerOnChange(fn: any) { this.onChangeCallback = fn;}
  registerOnTouched(fn: any) { this.onTouchedCallback = fn;}

  @Output()
  labelsChange: EventEmitter = new EventEmitter();

  removeValue(value:string) {
    var index = this.values.indexOf(value, 0);
    if (index != undefined) {
      this.values.splice(index, 1);
      this.labelsChange.emit(this.values);
    }
  }

  addValue(value:string) {
    if(!this.labelToAdd || this.labelToAdd.trim()===''){return;}
    this.values.push(this.labelToAdd);
    this.labelsChange.emit(this.values);
    this.labelToAdd = '';
  }
  
  //From ControlValueAccessor interface
  writeValue(value: any) {
      if (value !== this.values) {
          this.values = value;
      }
  } 

}


12/3/16

Flex Box And Prejudice

I don't know why some people have some superstitious feelings about using flex box css property. In this article I will try to convince you that using flex will make your life(as html programmer) much easier.
First of all i must recommend this great article that also supplies this great playground
For getting things easy to understand - I will start straight with some example:
lets say you need to build a page with following layout:
You have 2 groups of buttons - the one group should stick to the left and other one - should stick to the right. I want to show you two different ways to implement this layout:
HTML:


    
    <nav>
       <div class="left-menu">
          <button class="fa fa-refresh"></button>
          <button>Provisioning Events</button>
        </div>
        
       <div class="right-menu">
          <button>butt1</button>
          <button>butt2</button>
          <button>butt3</button>          
        </div>>         
    </nav>

CSS
1. using the "justify-content:space-between" css feature:

nav{
   display:flex; 
   justify-content:space-between;
}

2. using "flex:1" rule on style of .right-menu

nav{
   display:flex; 
}
.right-menu{
  flex:1;
  display:flex; 
  justify-content:flex-end;
}

What is "flex:1"?

"flex:1" shorthand for the flex-grow, flex-shrink and flex-basis properties, in our case means that .right-menu should capture all available space at the right of .left-menu.
Hope now you can see that flex-box feature has more various options to play with (more flexible after its name)...

One More Example

How to make footer to stick to bottom of the parent element? Lets say you have some kind of dialog with content and footer (which suppose to stick to the floor), and content need to "catch" all the remaining space?


   <div class="modal">
       <form>
         <main>
           content content content
           <br/>
           
           <div style="display:none;color:red" id="koko">
              something different here...
           </div>
         </main>
         <footer> 
           <button>footer</button>
         </footer>
       </form>
   </div>

So, Flex-Box can be helpful again:

.modal form{
  display:flex;
  flex-direction:column;
  height:230px;
  width:240px; 
  background:red;
  color:#fff;
}
main{  
  background:blue;
  flex:1;
}
#koko{
  height:170px;
  background:#fff;
}
footer{
  padding:5px;
}


JS Bin on jsbin.com

11/27/16

Export angularjs module

What are submodules?

When you writing angularjs application it is a good pattern to divide your app to submodules which are included into the main module as following:


angular.module('mainApp',['myApp.version','myApp.view1','myApp.view2'])

So it will be easy for testing or develop various parts of the application without each part need to knowing about other parts.
The directory structure of application usually place each submodule into its own directory:

.
├── view1
│   ├── view1.ts
│   └── view1.html


One of submodule "main" files contains angular module declaration:

    angular.module('myApp.view1', [
      'myApp.version.interpolate-filter',
      'myApp.version.version-directive'
    ])


How to import submodule into main typescript file?

It appears you can import code file which have no "export" syntax at all:


  //NO EXPORT AT ALL!
    angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', ($routeProvider: angular.route.IRouteProvider) => {
      $routeProvider.when('/view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
      });
    }])

    .controller('View1Ctrl', [() => {
    }]); 

Now in the main file - you can still use import syntax to include this code
app.ts

import './view2/view2';


Hope you have fun reading...

11/17/16

Organizing Your Angularjs Typescript Project

In one of my previous posts i found how to compile typescript files to javascript and i was very happy with myself because of my success. Since then i had little more experience with typescript. And now i have a few more points to share:

Using Import In Your Typescript Project

I have noticed many angularjs and angular2 projects using Import syntax. That way they not need to compile each file separately, instead you can compile only main file while all other files included in it (like in less or sass)
For exapmle :
Instead put all the things in your JS app.js file


//OOOOOLD STUFF.. BLAHHH
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

In typescript, you can move the config logic to its own separate config.ts file:

 export function config($locationProvider: ng.ILocationProvider, $routeProvider: angular.route.IRouteProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.otherwise({redirectTo: '/view1'});
  };



and import it to app.ts main file:

/// 
import { config } from './config';///<--HERE
module angularSeed {
'use strict';

  // Declare app level module which depends on views, and components
  angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.version'
  ]).config(config)

}
 

Import Is ES6 Syntax (Not Typescript!)

So, if you need to transpile your code either from ES6 and from typescript - i cannot think about other tool than webpack.

Weeeebpaaaack....
Webpack supports ES6 natively and for get it to compile typescript you only need to include ts-loader:
 
var webpack = require('webpack');
var path = require('path');
module.exports = {
    context: path.join( __dirname, '/app'),
    entry: 'app.ts',
    output: {
        filename: 'app.js',
        path: path.join( __dirname, '/app')
    },
    resolve: {
        root: path.join( __dirname, '/app'),
        extensions: ['', '.ts', '.webpack.js', '.web.js', '.js']
    },
    module: {
        loaders: [//<-- TYPESCRIPT, COOOL
        // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.ts?$/, loader: 'ts-loader' }
        ]
    }
}

Of course you need to include this webpack.config.js file in your project And update package.json with too more entries:
 
    "typings": "^0.8.1",
    "webpack": "1.13.1",
 

Build The Project

Since we using webpack now for build the project, the command to compile will be:


node_modules/.bin/webpack
 

Hope you have fun reading...
Visit my cool REPO

11/7/16

Presentational VS Container Components In React

What are Container Components?

There is rule for writing good & clear code - single responsibility.
Each code unit should depend as less as possible on other components (Should to care only about its own business in a human terms).
Thus it is good practice to separate code to self-containing units

Container Components are components which contains the logic of the component. Usually it contains in its markup one or more presentational components.

Presentational components are "dumb" components - they take care only about look of some part of data.

Example

Here is searchbar component


//Search Bar
import React, { Component, PropTypes } from 'react';
import {Link} from 'react-router';

let ResultsList = ({results, loading}) => {
        
      let createItem = function(repo, idx) {
        return <li key={idx}><Link to={`/repo/${repo.owner.login}/${repo.name}`}>{repo.name}</Link></li>;
      };
      let list;
      if(results && !loading) {
        list = results.length==0  ? 'no items yet' : results.map(createItem);
      } else {
        list = <div className="loader">Loading...</div>;
      }
      return <ul className="results">{list}</ul>;
             
}
export default ResultsList;

This code better to be refactored into smaller sub (Presentational)components

Refactoring:



import List from './List'
import Loading from './Loading'
import NoItems from './NoItems'
let ResultsList = ({results, loading}) => {
        
      return (<div>
        <Loading loading={loading}/>
        <List results={results}/>
        <NoItems results={results} loading={loading}/>
      </div>);
             
}

Here you can see that instead place logic and markup in the same place I made ResultsList to be Container which contains Loading List and NoItems presentational components

see code in this repo

11/1/16

Make React Component Code Shorter

In previous posts we created SearchPage component


class SearchPage extends Component {
      constructor(props) {
        super(props)
      }

      handleSearchTextChange(txt) {
        this.props.loadResults(txt);     
      }

      render() {
        const {results, loading} = this.props;
       
        return (
          <div>
            <SearchBar onChange={this.handleSearchTextChange.bind(this)}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};   

This code is working but, is there a way to make it more nicer and also more shorter?

The answer is "Yes"

First lets get rid of redundant "handleSearchTextChange" method:


class SearchPage extends Component {
      constructor(props) {
        super(props)
      }
      /*   
      handleSearchTextChange(txt) {
        this.props.loadResults(txt);     
      }
      */
      render() {
        const {results, loading} = this.props;
       
        return (
          <div>//<-- instead of "this.handleSearchTextChange.bind(this)"
            <SearchBar onChange={ this.props.loadResults}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};

or, even more simplier, lets take advantage of ES6 destructing syntax:

class SearchPage extends Component {
      constructor(props) {
        super(props)
      }

      render() {
        const {results, loading, loadResults} = this.props;//<--  loadResults method is one of the props too
       
        return (
          <div>
            <SearchBar onChange={loadResults)}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};

React Trick

There is a way in react to write a component much shorter is it has no other methods except render :


let SearchPage = ({results, loading, loadResults}) => {  
  return (
    <div>
      <SearchBar onChange={loadResults}/>
      <ResultsList results={results} loading={loading}/>
    </div>
  );
}

Thats all,far much shorter !

10/27/16

What Is Rebase Command Of Git For?

It is long time i working with git and i must admit i didnt figured out the meaning of Rebase command. Fortunately i hope i figured it now. It appears now that key point here is the git history.
It is important to keep each of commits to be as clear as possible - what is this commit about.

Sample

Let start with example repo where we have two issues open:
1. upgrade protractor library (technically to change version num in "package.json" file)
2. move some file from ES5 to the typescript
The common flow is that each bug/feature developed in its own branch and merged to the main "master" branch afterwards. Lets say the issues where split between two team members - mr X:

and mrs Y.

Mr X created branch named upgrade-protractor wile miss Y created view2-to-typescript at the same time.
Since mr X's task was much easier - he finished before miss Y, and committed his work. According the flow, mr X should do pool request, after that his changes where merged into master.
Now , after miss Y will finish her work and commit - she will face problem to merge her changes into master since it had changed meanwhile.

Good Old Merge

The simple way to handle the problem is to do

git merge master

which will create special "merged" commit because of merge action:
Now the view2-to-typescript has the protractor version change inside it and can be merged into master.
The disadvantage of this way is that commits log has a commit with changes which have nothing to do with the typescript task

Thats Where Rebase Came To Play

The nicer way to handle the merger-to-master problem is to do:


git rebase master

That way the history will be "rewritten" and only one commit with the relevant changes will appear in the commit log:

10/22/16

What is bindToController using for in angularjs?

If you start a new plunker by going to new -> angularjs -> 1.5.x you will get a starter template that attaches "name" property to the controller :


app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

and displays it in the template :

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
  </body>

controllerAs

Actually the more recommended way (look at john papa style guide) to attach some properties and methods to the controller - is by using controllerAs syntax:


app.controller('MainCtrl', function() {
  var ctrl = this;
  ctrl.name = 'World';
});

and the template should now be:

  <body ng-controller="MainCtrl as ctrl">
    <p>Hello {{ctrl.name}}!</p>
  </body>

(ctrl is recommended name to use in the controllerAs syntax by angular guys)

The problem with directives

When writing directives which has their own controllers we may use the controllerAs syntax as well:


app.directive('doSomething', doSomething);
function doSomething() {
  return {
    restrict: 'E',
    replace:true,
    scope:{}, //<--isolated scope
    template:'<button ng-click="ctrl.clickBtn()">click here</button>',
    controllerAs:'ctrl',
    controller: function() {
      var ctrl = this;
      ctrl.name = 'koko';
      ctrl.clickBtn = function() { 
        alert(ctrl.name);  //<--will alert 'koko'
      }
    }
  };
}

But what happens when we need the 'name' property to be passed from the outer scope, like below?

  ...
  scope:{name:'='}
  ...

How we make the controller to know about its new property?
Thats what the bindToController setting in the directive configuration are responsible for - to bind the outer scope members to the controller of directive:

 app.directive('doSomething', doSomething);
 function doSomething() {
  return {
    restrict: 'E',
    replace:true,
    scope: {
      name: '='
    },
    template:'<button ng-click="ctrl.clickBtn()">click here</button>',
    controllerAs:'ctrl',
    bindToController: true, //<-- HERE
    controller: function() {
      var ctrl = this;
      ctrl.clickBtn = function() { 
        alert(ctrl.name);   //<--will alert 'World'
      }
    }
  };
}


full code at this plunkr

Components

Since angular 1.5 introduced the Component method - we can take advantage of using the components to achieve the similar behavior:


app.component('somethingNewer', {
  bindings: {
    name: '='
  },
  template:'<button ng-click="ctrl.clickBtn()">click here</button>',
  controllerAs:'ctrl',
  controller: function() {
      var ctrl = this;
      ctrl.clickBtn = function() { 
        alert(ctrl.name); 
      }
  }
});

This code doing the same thing, but it shorter and its more like angular2
P.S.
controllerAs property if not specified - defined by default as $ctrl.
Hope you have fun reading...

10/10/16

Making Angular1 Seed Project To Work With Typescript

challenge

Since typescript became more and more popular those days i decided to try and take the following challenge: To convert this angular1. seed-project from old fashioned ES5 to Typescript.
I have very little experience with typescript, and that why it is interesting. This project consist only from two basic views so it seems to be not so hard...

Typings

First we need to add typings to our project. What are those typings?
Typings are dependencies as angular or angular-routes libraries which translated to typescript
First step we need to add typescript & typings dependencies to package.json file


"typescript": "^1.8.10",
"typings": "^0.8.1",

Lets also add typings.json file which has list of Definitions of libraries we use in project

{
  "ambientDependencies": {
    "angular": "registry:dt/angular#1.5.0+20160412133217",
    "angular-route": "registry:dt/angular-route#1.3.0+20160317120654",
    "jquery": "registry:dt/jquery#1.10.0+20160417213236"
  }
}

After adding those files lets update again the package.json file so it will install typings after installing all dependencies:

...
  "scripts": {
    "postinstall": "bower install && typings install",
    ...
   }
...

Lets check - after runing npm i command the "typings" directory should appear:

Compiling

The compile command of typescript you need to call for convert your ts files into js is "tsc -p ./".
tsc takes other options of how to compile typescript from tsconfig.json file:


{
  "compileOnSave": false,
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5"
  },
  "exclude": [
    "bower_components",
    "node_modules",
    "typings"
  ]
}

It is convenient to configure package.json "scripts" zone so you can run the tsc with npm:
npm run build

..
  "scripts": {
   "build": "tsc -p ./",
    ...
   }
...

Change the code to typescript

Now you can start to convert the project to typescipt:
First - lets start with view1.js file , by rename it to view1.ts


/// <reference path="../../typings/main/ambient/jquery/index.d.ts" />
/// <reference path="../../typings/main/ambient/angular/index.d.ts" />
/// <reference path="../../typings/main/ambient/angular-route/index.d.ts" />
angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', ($routeProvider: angular.route.IRouteProvider) => {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', [() => {

}]); 

See that after running "npm run build" the view1.js file generates!

see full code here: repo
Thanks for reading

9/29/16

Redux - the blitz

I have heard a lot about redux but never had time to put my hands on it., so i guess the time is come - lets write something about redux.

So, what is redux?

To put the long terms short - it is a way to organize logic which changes the state (application data) of single page application. So if you asking yourself: is redux about to make me write less code? - Well, the answer is no, this is not the point. The point is - to make clear for developer who and why changed the state of app.

Three Basic Principles Of Redux

According to what the documentation say, three basic principles of redux are:
1. Single source of truth( single store )
2. State is read-only
3. Changes are made with pure functions (reducers)
For implementing the redux into our search app we will use react-redux library.

Lets Talk About Three Primary Modules Of React-Redux

Store

Most important module there all application data (or state) is stored:
initial state:


export default {
    results: [],
    loading: false
}

...
...
...
const rootReducer = combineReducers({
  results: searchResults,
  loading
});

export default rootReducer;

...
...
...
export default function configureStore(initialState) {
  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(thunk, reduxImmutableStateInvariant())
  );
}

Actions

A way by which components can "talk" with store, explaining what exactly gonna happen.
search action:


export function loadResultsSuccess(results) {
  return { type: 'LOAD_RESULTS_SUCCESS', results};
}

export function loadResults(query) {
  return function(dispatch) {
     let url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
     
     return  fetch(url)
        .then(function(response) {
         return response.json();
        })
        .then((result) => {
            let results;
            if (result.items.length !== 0) { 
               results = result.items.slice(0,5);
            } else {
               results = [];
            }
            //DISPATCH RESULTS
            dispatch(loadResultsSuccess(results));
        });
  };
}

Reducers

Should get the info from action and return new state object which generated from the original state, but without mutating it.


import initialState from './initialState';

export default function searchReducer(state = initialState.results, action) {
  switch (action.type) {
    case 'LOAD_RESULTS_SUCCESS':
      return action.results;

    default:
      return state;
  }
}

Make The Appllication To Work With Stuff Was Just Created

Lest modify our SearchPage so, it will dispatch "search" action instead of calling "loadResults" method (which duty was to load the search results from the request and put the to the state):
SearchPage component:


import React, { Component, PropTypes } from 'react'
import SearchBar from './mySearchBar';
import ResultsList from './myResultsList';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as searchActions from './actions/actionSearch';

class SearchPage extends Component {
      constructor(props) {
        super(props)
      }

      handleSearchTextChange(txt) {
        this.props.loadResults(txt);//<---HERE      
      }

      render() {
        const {results, loading} = this.props;
       
        return (
          <div>
            <SearchBar onChange={this.handleSearchTextChange.bind(this)}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};
    

function mapStateToProps(state, ownProps) {
  return {
    results: state.results,
    loading: state.loading
  };
}

function mapDispatchToProps(dispatch) {
  return {
    loadResults: bindActionCreators(searchActions.loadResults, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SearchPage);   

See the full code on the repo

8/30/16

Using React Router

Like in angular react has its own router module. For demonstration usage of routes in our application, lets create route repo there user can see the details of one of repos which displayed in search results.
Instead of simple li elements the search results will display links to repo route.
The main application will also have its own route - the default "/".

    ReactDOM.render(
       <Router history={hashHistory}> 
         <Route path="/" component={SearchPage}></Route>
         <Route path="repo/:owner/:repo" component={Repo} />
       </Router>,
        document.getElementById('example')
      );
Repo route will have its own component - Repo comonent, there will be displayed details of selected repo

    var Repo = withRouter(
      React.createClass({

        render: function() {
          return (
            <ul>
              <li><strong>owner</strong>:{this.props.params.owner}</li>
              <li><strong>repo</strong>:{this.props.params.repo}</li>
              <a href="#/">back</a>
            </ul>
          );
        }
      })
    );
    
Now the only thing left is modify the SearchResults components so it ill display links to repos:


    // Results List
    var ResultsList = React.createClass({
 
      render: function() {
        
          var createItem = function(repo, idx) {
           return <li key={idx}><Link to={`/repo/${repo.owner.login}/${repo.name}`}>{repo.name}</Link></li>;
          };
          var list;
          if(this.props.results && this.props.results.length && !this.props.loading) {
            list = this.props.results.map(createItem);
          } 
          return <ul className="results">{list}</ul>;
        
      }
    });

See the code on plnkr

8/16/16

React - Organizing the project

How To Organize the Project

Yes, we created little app using the react library. For simplicity i used (already removed in latest babel version) browser module of babel-core which compiles the react in the browser. Thats not ideal way of writing react aps(compiling in the browser is heavy operation that can be done using some task running tool instead).

Using Webpack

There are many tools which can do the react compilation job. One of those tools is a well known webpack which we will use for this post

Installing Webpack

For be able to run webpack you must have nodejs installed on your machine.
Lets run this command in the console for install webpack globally


   npm install webpack -g
Now you able to bundle your javascript files into one js file named "bundle.js" with single console command

webpack ./app.js app.bundle.js
Instead of specify parameters in the command line, better attitude is to specify them in wepack.config.js file:

 module.exports = {
     entry: './src/app.js',
     output: {
         path: './bin',
         filename: 'app.bundle.js'
     }
 };
Tha way the command is way more shorter:

webpack //thats it

Dependencies

Since we will create react application we will need to install various dependencies (like babel) which will help us to compile and run our project. It is good practice to store list of dependencies in package.json file, so npm module of nodejs will be able to install them at once using single command npm install.
For creating package.json file run:


npm init 
Will promp you with various questions about your project, currently you may answer "yes" (by pressing ENTER) on all of them. finally package.json file will be created in your root directory.
From now each module we will install - will be listed in the package.json file:

 npm i react react-dom --save
package.json :

{
  "name": "webpack project",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.3.0",
    "react-dom": "^15.3.0"
  }
}

babel

Since react contains some features that not supported by some browsers (like jsx) we will use babel library:


npm install --save-dev babel-loader babel-core babel-preset-react
So our wepack.config.js file will finally look like:

 module.exports = {

     entry: './src/app.js',
     output: {
         path: './out',
         filename: 'app.bundle.js',
     },
     module: {
         loaders: [{
             test: /\.js?|\.jsx?$/,
             exclude: /node_modules/,
             loader: 'babel',
             query: {
                presets: ['react']
             }             
         }]
     }
 }
Now our project configured in the way so when user runs

webpack
command in the console-
it compiles every javascript (.js) file and it puts the results inside out directory in single file app.bundle.js, isnt that cool?

Project Structure

After we created the minimalistic configuration, lets take a care about files that are part the project itself:
app.js file where we will place our (need to be compiled) javascript code (lets put it in the "src" directory) and index.html - the main html file of our single page app which will refer the compiled results of javascript:


 <!DOCTYPE html>
 <html>
     <head>
         <meta charset="utf-8">
     </head> 
     <body>
         <div id="example"></div> 
         <script  src="out/app.bundle.js" charset="utf-8"></script>
     </body>
 </html>
Now lets paste the app code into the app.js file

var React = require('react');
var ReactDOM = require('react-dom');
var $ = require("jquery");

//Search Bar
var SearchBar = React.createClass({
  
  onChange: function(e) { 
    // console.log(e.target.value)
    this.props.onTextChange(e.target.value);
  }, 
  render: function() {
    return (
      <div><input placeholder="type search term" onChange={this.onChange}/></div>
    );
  }
});   
// Results List
var ResultsList = React.createClass({

  render: function() {
    
      var createItem = function(item, idx) {
        return <li key={idx}>{item.text}</li>;
      };
      var list;
      if(this.props.results && this.props.results.length && !this.props.loading) {
        list = this.props.results.map(createItem);
      } else if(this.props.results.length==0  && !this.props.loading){
        list = 'no items yet';
      } else if(this.props.loading) {
        list = <div className="loader">Loading...</div>;
      }
      return <ul className="results">{list}</ul>;
    
  }
});
//Search Page
var SearchPage = React.createClass({
  getInitialState: function() {
    return {results: [],loading:false};
  }, 
  loadResults: function(query){
    this.setState({loading:true});
    
    var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
    $.get(url)
    .then(function (result) {
      
      if(result.items.length!==0){ 
        var results = result.items.map(item => { 
          return   {text: item.name}
        }).slice(0,5);
        
      }
      this.setState({loading: false, results:results});
    }.bind(this));//<-- important to bind this for use "setState"
    
  },
  handleSearchTextChange: function(txt){

    this.loadResults(txt)
    
  },
  render: function() {
    return (
      <div>
        <SearchBar onTextChange={this.handleSearchTextChange}/>
        <ResultsList results={this.state.results}  loading={this.state.loading}/>
      </div>
    );
  }
});
    
ReactDOM.render(
    <SearchPage />,
    document.getElementById('example')
);
module.exports = SearchPage;

jquery

the last thing left is to add jquery library to the project


 npm install --save jquery 
After jquery is included and project compiled you can run it with

webpack-dev-server
The developer server of webpack.
Here is link to repo with the code.
Hope you have fun reading

8/13/16

React - Building Search App (Part 6)

Last Finishes

Our app looks great now, but there some more things we could improve:
For example- when the user has not performed any search yet it is good to display no items yet message instead of "some item".
Lets modify Results List component accordingly:


    
     // Results List
    var ResultsList = React.createClass({
 
      render: function() {
        
          var createItem = function(item, idx) {
            return 
  • {item.text}
  • ; }; var list; if(this.props.results && this.props.results.length) { list = this.props.results.map(createItem); }else{ // <--- no search results came from server list = 'no items yet'; } return
      {list}
    ; } });

    Displaying loading animation

    It is good practice to display animation when request sent but results hasn't come back yet.
    That way user will notified that his actions were noticed and the the server working to fulfill his request.
    That means we should pass another property from SearchPage to ResultsList component - loading which will "tell" the results component when request started and when it finished (e.g. when to show loading animation):

    
    
         loadResults: function(query){
            if(query==''){
              this.setState({
                loading: false, 
                results:[]
              });
              return;
              
            }
            
            this.setState({loading:true}); // <--- the request started so animation must be visible
            var results = [];
            
            var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
            $.get(url)
            .then(function (result) {
             
              if(result.items.length!==0){ 
                results =result.items.map(item => { 
                  return   {text: item.name}
                }).slice(0,5);
                
              }else{
                results = []
              }
             this.setState({loading: false, results:results});
            }.bind(this));//<-- important to bind this for use "setState"
            
          }
           ...
           ...
           ...
          render: function() {
            return (
              <div >
                 <SearchBar onTextChange={this.handleSearchTextChange}/ >
                 <ResultsList results={this.state.results}  loading={this.state.loading}/ > //<---passing loading property to ResultsList component
               </div >
            );
          }
    

    Animation

    i will add to project the CSS code i took from this awesome project so it will display spinner animation:

    
    
    .loader {
      margin: 20px auto;
      font-size: 10px;
      position: relative;
      text-indent: -9999em;
      border-top: 1.1em solid rgba(6,178,103, 0.2);
      border-right: 1.1em solid rgba(6,178,103, 0.2);
      border-bottom: 1.1em solid rgba(6,178,103, 0.2);
      border-left: 1.1em solid #06b267;
      -webkit-transform: translateZ(0);
      -ms-transform: translateZ(0);
      transform: translateZ(0);
      -webkit-animation: load8 1.1s infinite linear;
      animation: load8 1.1s infinite linear;
    }
    .loader,
    .loader:after {
      border-radius: 50%;
      width: 5em;
      height: 5em;
    }
    @-webkit-keyframes load8 {
      0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
      }
    }
    @keyframes load8 {
      0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
      }
    }
    
    
    After adding the animation css, we need to modify the ResultsList component code so it will be able to display the animation:
    
        // Results List
        var ResultsList = React.createClass({
     
          render: function() {
            
              var createItem = function(item, idx) {
                return <li key={idx}>{item.text}</li>;
              };
              var list;
              if(this.props.results && this.props.results.length && !this.props.loading) {
                list = this.props.results.map(createItem);
              } else if(this.props.results.length==0  && !this.props.loading){
                list = 'no items yet';
              } else if(this.props.loading) {
                list =  <div className="loader">Loading... </div>;
              }
              return  <ul className="results">{list} </ul>;
            
          }
        });
    

    Now the animation is displayed

    the code on plnkr
    Hope you have fun reading

    8/9/16

    React - Building Search App (Part 5)

    Ajax

    In previous parts we have created react functioning application that consists from 3 components, which can communicate and respond to events, but what kind of app is this if it only displaying some static data?
    Of course we need to do to some server request for bring some real data.
    Unlike angular that has its own http service, react doesn't have helper functions for ajax and this due to its convention - to be lighter as possible.
    Fot quickly write a code that makes ajax request we will use good old jquery library. Instead of build some server for serve us data we will take an advantage of awesome github api
    For example following api will get you repositories those names contains some characters you specified as search param:

    
       var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
       $.get(url, function (result) {
          //result.items will contain repositories corresponding to query
       })
    

    Make a Request

    Now the only thing left is to get the request to play with the other code:

    
        //Search Page
        var SearchPage = React.createClass({
          getInitialState: function() {
            return {results: [{text:'some result'}]};
          }, 
          loadResults: function(query){
            
            var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
            $.get(url, function (result) {
              if(result.items.length!==0){
                var results = result.items.map(item => { 
                  return   {text: item.name};//<--- for our app we need each item to have "text" property
                }).slice(0,5);
                this.setState({results:results});
              }
            }.bind(this));//<-- important to bind this for use "setState"
          },
          handleSearchTextChange: function(txt){
    
            this.loadResults(txt)//<--- calling the request with search term passed from search input
           
          },
          render: function() {
            return (
              <div>
                <SearchBar onTextChange={this.handleSearchTextChange}/>
                <ResultsList results={this.state.results}  />
              </div>
            );
          }
        });
    
    Note that for pass the results to ResultsList component we need only to modify the state using the setState method.

    view the code
    Hope you have fun reading

    8/7/16

    React - Building Search App (Part 4)

    Events

    So, in previous part we learned about props and state, and our search app already able to display some results.
    The results are came from parent SearchPage component, passed to ResultsList child component which displays them.

    But what about SearchBar component? Isnt it suppose to play the key role in the app? Well, indeed SearchBar suppose to pass user input when somebody search for something and typing-in some chars. SearchBar should speak to SearchPage and it should perform search and pass the results to ResultsList

    Handle Text Change

    For to catch user input of search input box you must specify handler in the onChange attribute:

    
        var SearchBar = React.createClass({
         
          onChange: function(e) {
            console.log(e.target.value);
          }, 
          render: function() {
            return (
              <div><input placeholder="type search term" onChange={this.onChange}/></div>
            );
          }
        }); 
    
    Now you can see the console prints the chars user enters. Yo ho!@!@!

    Pass the input to the parent component

    Lets take an advantage of the technique we just learned in previous part - lets use the props. But how? We can modify state but we should avoid from trying to update the props from inside the component!
    Actually we not have to modify things for passing data - instead of placing some usual javascript variable into attribute (prop) as we did with ResultsList component, we can set the prop with the function!

    
        //Search Page
        var SearchPage = React.createClass({
          getInitialState: function() {
            return {results: [{text:'some result'}]};
          }, 
          handleSearchTextChange: function(txt){
            console.log(txt)
          },
          render: function() {
            return (
              <div>
                <SearchBar onTextChange={this.handleSearchTextChange}/>//<---here is the magic!
                <ResultsList results={this.state.results}  />
              </div>
            );
          }
        });
        
    
    Now the only thing left is to modify SearchBar the way it will use the passed function :
    
        var SearchBar = React.createClass({
         
          onChange: function(e) {
            this.props.onTextChange(e.target.value);
          }, 
          ...
        }); 
    
    Now we just make SearchBar to be able to speak to its parent SearchPage!
    see plnkr
    If you find this stuff interesting - continue to the next post

    8/3/16

    React - Building Search App (Part 3)

    Props(Properties)

    Props are the attributes which can be accessible from inside the react component.
    For our example we can define the results list array and put it in the results property (attribute) of ResultsList component.
    First step: lets modifiy ResultsList components so it will able to display array of results:

    
    
        // Results List
        var ResultsList = React.createClass({
          //this.props.results should be set with array of search results 
          render: function() {        
              var createItem = function(item, idx) {
                return <li key={idx}>{item.text}</li>;
              };
              return <ul className="results">{this.props.results.map(createItem)}</ul>;
            
          }
        });
    
    Now lets set the results attribute of ResultsList component with some static data:
    
    
      //Search Page
        var SearchPage = React.createClass({
        
          render: function() {
            return (
               <div>
                 <SearchBar/>
                 <ResultsList results={[{text:'some result'}]}  />
               </div>
            );
          }
        });
    
    
    The result is - we can see the results are displayed:
    see code:plnkr

    State

    Of course the results should not be set that way - statically inside the markup.
    They should be defined as member of SearchPage component. For make it accessible for the markup in react we must use state.

    
    
      //Search Page
        var SearchPage = React.createClass({
          getInitialState: function() {
            return {results: [{text:'some result'}]};
          },   
          render: function() {
            return (
               <div>
                 <SearchBar/>
                 <ResultsList results={this.state.results}  />
               </div>
            );
          }
        });
    
    

    Summary

    So now we learned about props and state, and how SearchPage component, communicates with its ResultsList child component. If you find this stuff interesting - continue to the next post

    8/2/16

    React - Building Search App (Part 2)

    Nested Component

    So after we learned that react is components and created our first component - lets see how components may host other components inside themselves:
    Lets create SearchBar component which be child component of SearchPage and which will include search text input:

    
    
        var SearchBar = React.createClass({
          render: function() {
            return (
              <div><input placeholder="type search term"/></div>
            );
          }
        });  
         var SearchPage = React.createClass({
          render: function() {
            return (
              <div>
                  <SearchBar/>
              </div>
            );
          }
        });
        
        ReactDOM.render(
            <SearchPage />,
            document.getElementById('example')
          );
    
    And lets add another child component which will hold the list of search results:
    
    
         // Results List
        var ResultsList = React.createClass({
          render: function() {
            return (
              <div className="results">here will come search results.. </div>
            );
          }
         });
    
         ...
         ...
      
         var SearchPage = React.createClass({
          render: function() {
            return (
              <div>
                 <SearchBar/>
                 <ResultsList/>
              </div>
            );
          }
        });
    
    
    Note that in react if you want specify some css class you need to use className

    Communication

    Ok, you asking yourself, but how those components will communicate one with other?
    How searchBar will tell the resultsList to display results?
    - Here are two words you must remember when you talking about component communication in react:
    props and state , we will talk about them in the next part

    7/29/16

    React - Building Search App (Part 1)

    Get Started

    So, if you asking yourself how is it feels to program react - you may easily create your first react app withing seconds:

    1. go to plunker
    2. click on the down arrow in the green button on the top with caption "new"
    3. select "react" or "react with addons" and yes, you have created your first react app!
    Yes, it currently only says "Hellow World", but from this second no man can say you never programmed react...

    Components are basic part of react

    When building React app you must start from building components. So lets create our first component - searchPage

    
         var SearchPage = React.createClass({
          render: function() {
            return (
              <div>here will come search results...</div>
            );
          }
        });
        
        ReactDOM.render(
            <SearchPage />,
            document.getElementById('example')
          );
    
    running code
    Thats it - was not too complicate, right? If you want to get more of this stuff - follow the next part

    7/21/16

    Building A Short-Description Pipe Angular 2

    Pipe is same thing that filter in angluar1. Lets take a look on code that checks if field has too much characters and if it has - replaces the extra characters with ... :

    
    import { Pipe } from '@angular/core';
    
    @Pipe({
      name: 'short_description'
    })
    export class ShortDescriptionPipe {
      transform(value) {
        let transformedValue;
        if (value && value.length > 100) {
          transformedValue = `${value.substring(0, 100)}...`;
        } else {
          transformedValue = value;
        }
    
        return transformedValue;
      }
    
    
    
    Now if we have some field contain more than 100 characters it will display only first 100 characters
    
        <div>
          <h2>Hello {{name | short_description }}</h2>      
        </div>
    
    

    Extending The Pipe To Get "Maximum Chars" Param

    In previous code the characters length is statically restricted to 100 chars. But what if we wish to dynamicaaly pass the maximum chars number?

    
        <div>
          <h2>Hello {{name | short_description : 4}}</h2>      
        </div>
    
    As in angular1 the pipe params prefixed with ::
    
    import { Pipe } from '@angular/core';
    
    @Pipe({
      name: 'short_description'
    })
    export class ShortDescriptionPipe {
      transform(value, args?) {//args contains param
        if(!args ){
          args= 100;
        }
        let transformedValue;
        if (value && value.length > args) {
          transformedValue = `${value.substring(0, args)}...`;
        } else {
          transformedValue = value;
        }
    
        return transformedValue;
      }
    
    
    

    7/11/16

    3 Different Ways To Use ngFor

    Introduction

    Like ng-repeat directive of angular 1. there is ngFor directive in angular2. it uses for display lists of items.
    For example sake - lets take situation we need to display table of site users.
    In old angular1 the template should look like this:
    angular1 template

    
        <div>
          <h2>{{name}}</h2>
          <div  ng-if="userList.length===0">No Users Yet</div>
          <table ng-if="userList.length" >
            <tr><th>First Name</th><th>Last Name</th></tr>
            <!-- Look here -->
            <tr ng-repeat="user in userList">
             <td>
               {{user.firstName}}
             </td>
             <td>
               {{user.lastName}}
             </td>         
            </tr>
          </table>
        </div>
    
    
    And here is controller & service code:
    angular1 code
    
       //service 
       app.factory('usersSrv', function($http, $q) {
         function get(){
           var defer = $q.defer();
           $http.get('./users.json').success(function(data){
             defer.resolve(data)
           });
           return defer.promise;
         }
      
         var service = { 
            getUsers: get
         }
    
         return service;
       });
        //controller:
       $scope.userList = [];
       usersSrv.getUsers().then(function(users){
        $scope.userList = users; 
       })
    
    
    Code: plunkr


    The same scenario could be written in angular2 like this
    template of app.component.ts
    
          <table *ngIf="userList.length">
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
            <!-- Look here -->
            <tr *ngFor="let user of userList">
             <td>
               {{user.firstName}}
             </td>
             <td>
               {{user.lastName}}
             </td>         
            </tr>
          </table>
    
    
    If there are some users in our db - they will be shown in table.
    Currently the data taken from static array:
    
    export class App {
      public userList:Array=[];
      constructor(userService:UserService) {
        this.name = 'Users Table:'
        this.userList =  [{firstName:'Vasia', lastName:'kozlov'}]
      }
    }
    
    
    we can see users table and everything is fine.

    Code: plunk

    Promise

    The things starting to be more complicate when users collection is loaded from http request. It is complicate because users data now is asyncronous.
    So, the first way to handle this thing is to use good old Prmoise known to us well from angular1.
    Unlike angular1 we need to import toPromise operator of rxjs library.
    users.servise.ts:

    
    import { Injectable }    from '@angular/core';
    import { Headers, Http } from '@angular/http';
    import 'rxjs/add/operator/toPromise';//import of "topromise" method from rxjs lib
    
    @Injectable()
    export class UserService {
      private url:string = './users.json';
      constructor(private http: Http) {}
      getUsers(): Promise {//method must return promise
        return this.http.get(this.url)
        .toPromise()
        .then(response => response.json());
      }
    }
    
    
    Now in the component code we able to use the "then" method for getting the callback of asyncronous method.
    app.component.ts:
    
    import {Component} from '@angular/core';
    import {UserService} from './user.servise';
    @Component({
      selector: 'my-app',
      providers: [],
      template: `
          ...
          ...
          ...
      `,
      providers: [UserService]
    })
    export class App {
      public userList:Array=[];
      constructor(userService:UserService) {
        this.name = 'Users Table:'
        userService.getUsers().then(//Here we can use "then"
          users => this.userList=users,
          error => console.log(error)
        );
      }
    }
    
    
    The good side here (for me) is that it very similar to angular1 way.
    Code: plunk

    Subscribe

    The second attitude is to use map method of rxjs library.
    users.servise.ts:

    
    import { Injectable }    from '@angular/core';
    import { Headers, Http } from '@angular/http';
    import 'rxjs/Rx';
    
    @Injectable()
    export class UserService {
      private url:string = './users.json';
      constructor(private http: Http) {}
      getUsers() {
        return this.http.get(this.url).map(response => response.json());
      }
    }
    
    
    This map method returns Rx.Observable object, thus in component code we will need to use subscribe for handle the async data:
    app.component.ts:
    
    import {Component} from '@angular/core';
    import {UserService} from './user.servise';
    @Component({
          ...
          ...
          ...
      providers: [UserService]
    })
    
    export class App {
      public userList:Array=[];
      constructor(userService:UserService) {
        this.name = 'Users Table:';
        userService.getUsers().subscribe(
          users => this.userList=users,
          error=>console.log(error)
        );
      }
    }
    
    
    I like this way because it looks more shorter (no need to use conversion to promise like in previous way).
    Code: plunk

    Using Async Pipe

    Unlike in angular1 there is a way in angular2 to pass observable collection directly to ngFor directive.
    We can do this using angular2 async pipe.
    template of app.component.ts

    
        <div>
          <h2>{{name}}</h2>
          <div  *ngIf="userList.length===0">No Users Yet</div>
          <table >
            <tr><th>First Name</th><th>Last Name</th></tr>
            <!-- Look here -->
            <tr *ngFor="let user of userList | async">
             <td>
               {{user.firstName}}
             </td>
             <td>
               {{user.lastName}}
             </td>         
            </tr>
          </table>
        </div>
    
    
    Usinp async pipe makes the component code even more shorter: app.component.ts:
    
    import {Component} from '@angular/core';
    import {UserService} from './user.servise';
    @Component({
          ...
          ...
          ...
      providers: [UserService]
    })
    
    export class App {
      public userList:Array=[];
      constructor(userService:UserService) {
        this.name = 'Users Table:';
        //no subscribe needed
        this.userList=userService.getUsers();
      }
    }
    
    

    Little More About Async Pipe

    Another cool thing about this pipe is - that it can be used not only in ngFor
    For example - if you need to show "No Users Yet" message when no users found in DB, you may use async pipe too:
    template of app.component.ts

    
        <div>
          <h2>{{name}}</h2>
          
          <!-- HERE -->
          <div  *ngIf="(userList | async)?.length===0">No Users Yet</div>
          <table *ngIf="(userList | async)?.length>0">
            <tr><th>First Name</th><th>Last Name</th></tr>
            <tr *ngFor="let user of userList | async">
             <td>
               {{user.firstName}}
             </td>
             <td>
               {{user.lastName}}
             </td>         
            </tr>
          </table>
        </div>
    
    

    Code: plunk

    Hope you have fun reading...

    6/20/16

    ChangeDetectionStrategy

    Many js frameworks have way to watch changes on the javascript models and project them to the html.
    In angular 1. this done by digest cycle.
    In Angular2 this done by using zone.js
    ChangeDetectionStrategy is how angular2 tracking run time changes of the model and projecting them to the DOM.
    To be more precisely: framework will check components only when their inputs change or components' templates emit events.

    example (or usecase)

    Say we need to create upper menu component. In case that user not logged in it should display "login" link, and once somebody logged in - "logout" link should be displayed.

    
        <li><a [routerLink]="['/Login']" *ngIf="!(getLoggedIn() | async)">Login</a></li>
        <li><a href="#" (click)="logout()" *ngIf="getLoggedIn() | async">Logout</a></li>
    
    
    So far things are pretty simple only inner model of component changes, and it is changes after request observable fires an event.
    
      changeDetection: ChangeDetectionStrategy.OnPush
    
    That is good practice to tell angular not to track any other changes on the model since there could not be changes This way angular will work much quicker.
    
    import { Component, ChangeDetectionStrategy } from '@angular/core';
    import { ROUTER_DIRECTIVES, Router } from '@angular/router-deprecated';
    
    import template from './menu.template.html';
    import { UserService } from '../../../auth';
    
    @Component({
      selector: 'top-menu',
      template: template,
      directives: [ROUTER_DIRECTIVES],
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    ...
    
    

    6/15/16

    Form Validation In Angular2

    Hi, My today's challenge is to create simple login form, like you can see in almost every web application.
    Well, we will use plunker project already created for previous post since it has view called "login". Lets also add css styles of bootstrap library to the project for take advantage of this awesome framework with its form and validtaion styles.

    Step 1 - ngModel

    Yes, the famous two way data binding is still here. Only now it is using "[(" syntax:

    
       <form (ngSubmit)="login()">
          <div class="form-group">
            <label for="email">Email</label>
            <input type="text" class="form-control"
              [(ngModel)]="email"
                >
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input type="password" class="form-control"
              [(ngModel)]="password"
               >
          </div>
    
          <button type="submit" class="btn btn-default">Submit</button>
      </form>
    
    
    lets put simple code of component which only checks the input value is bound correctly:
    
    export class Login {
      public  email: string;
      public  password: string;
      constructor(public router: Router){}
      login(){
        if(this.email && this.password){
           alert(this.email+' '+this.password)
        }
      }
    }
    
    
    Now when some characters filled into both inputs you can see it in alert after clicking submit.

    Step 2 - ngForm

    It is good practice to use "ngForm" directive which holds the status of form and its controls: The status can be valid (or "invalid"),pristine(or dirty) and touched
    By using reference (attribute decorated with "#") and "hidden" directive i can show validation error labels.

    
     <div class="container">
       
       <form (ngSubmit)="login()">
          <div class="form-group">
            <label for="email">Email</label>
            <input type="text" class="form-control"  required
              [(ngModel)]="email"   ngControl="emailctrl" #emailctrl="ngForm"
                >
            <div [hidden]="emailctrl.valid || emailctrl.pristine" class="alert alert-danger">
              Email is required
            </div>
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input type="password" class="form-control"  required
              [(ngModel)]="password"  ngControl="passctrl" #passctrl="ngForm"
               >
            <div [hidden]="passctrl.valid || passctrl.pristine" class="alert alert-danger">
              Passwd is required
            </div>           
          </div>
    
          <button type="submit" class="btn btn-default">Submit</button>
      </form>
      </div>
    
    
    From now - if you typing something in one of the controls and then deleting it - the validation messages displayed.

    Here is running code: Hope you have fun reading...

    6/10/16

    Creating Preloader In Angular2 app

    Current Challenge

    Many sites and webapps have some cool animation that plays before all the site resources (like css, scripts and other stuff) fully loaded.
    You see this cool animation (or progress bar) playing for some time and then all the site elements appear.(Instead of staring in some blank page)
    In this post i decided to find out how to create such animation in my angular2 experimental site.

    Preloader animations

    First of all - for making some animation you must create a proper CSS code. Since i have no time and talent to make this CSS by myself, i made a shortcut and used this cool css preloaders site for taking CSS of one of its awesome animations.

    
    .spinner {
      width: 40px;
      height: 40px;
      background-color: #333;
    
      margin: 100px auto;
      -webkit-animation: sk-rotateplane 1.2s infinite ease-in-out;
      animation: sk-rotateplane 1.2s infinite ease-in-out;
    }
    
    @-webkit-keyframes sk-rotateplane {
      0% { -webkit-transform: perspective(120px) }
      50% { -webkit-transform: perspective(120px) rotateY(180deg) }
      100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
    }
    
    @keyframes sk-rotateplane {
      0% { 
        transform: perspective(120px) rotateX(0deg) rotateY(0deg);
        -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg) 
      } 50% { 
        transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
        -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg) 
      } 100% { 
        transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
        -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
      }
    }
    
    

    HTML element

    To make this animation to work we need to put its "spinner" class on some html element that will appear on the view before main application component loaded and will disappear immediately afterwise.
    To achieve this effect we can put this element inside the main component tag, so after its contents will load - the inner element will be simply overriden

    
        <my-app>
          <div class="spinner"></div>
        </my-app>
    
    
    Thats it - we achieved our goal without writing even single angular2 line! It little bit disappointing but it also good practice to do things as simple as possible

    Here is running code: Hope you have fun reading...

    5/25/16

    Routes In Angular2 (Part 2)

    In previous post we talked about routes in angular2. We saw some basic example of app using routes. But what about nested routes?

    Nested Routes

    Lets say for example that we need in our application to have a login page which has no menus on it. After passing authentication user should be redirected to protected pages which have the same menus on each of them:

    Step 1

    Transfer application to use nested routes is very easy.
    First you need to create the middle ware route which will host its own routes directive on it. Lets call it layout.
    On this middle ware view we will locate the menu.
    
    import {Component} from 'angular2/core'
    import {RouteConfig, Router, Route,  ROUTER_DIRECTIVES} from 'angular2/router';
    ...
    @Component({
      selector: 'layout',
     template: `
        <h2>Hello {{name}}</h2>
        <!-- menu is located here now -->
        <a [routerLink]="['Layout']">Dashboard</a> | 
        <a [routerLink]="['Reports']">Reports</a> |
        <a [routerLink]="['Login']">Login</a>
        <hr>
       <!-- router directive -->
       <router-outlet></router-outlet>, 
     directives: [ROUTER_DIRECTIVES]
    })
    
      
    @RouteConfig([
       new Route({path: '/', name: 'Dashboard', component: Dashboard, useAsDefault:true}),
       new Route({path: '/reports', name: 'Reports', component: Reports})
    ])
    export class Layout {
      constructor(){
        this.name = 'Angular2 Nested Routes';
      }
    }
    
    

    Step 2

    Next thing lets create the login page which will located at the base root route "/login".
    
    import {Component} from 'angular2/core'
    
    @Component({
      selector: 'login',
     template: `
       <div>
         <h1>Please Log In</h1>
         <div style="text-align:center">
               username:<input> 
         </div>
         <div style="text-align:center">
               password:<input> 
         </div>
         <div style="text-align:center">
          <button (click)="login()">login</button>
        </div>
       </div>  `
    })
    
    export class Login {
      constructor(public router: Router){}
      login(){
        this.router.navigate(['Layout']);
      }
    }
    
    
    
    Also lets create the Dashboard page which will located at the inner route "layout/dashboard".

    Step 3

    Last thing we should modify the root "app" component so it will support nested routes:
    
    import {Component} from 'angular2/core'
    import {RouteConfig, Router, Route,  ROUTER_DIRECTIVES} from 'angular2/router';
    import {Layout} from './layout';
    import {Login} from './login';
    
    
    @Component({
      selector: 'my-app',
      template: `
          <router-outlet></router-outlet>
      `,
      directives: [ROUTER_DIRECTIVES]
    })
    @RouteConfig([
       new Route({path: '/layout/...', name: 'Layout', component: Layout}),
       new Route({path: '/login', name: 'Login', component: Login}),
       {
        path: '/**',
        redirectTo: ['Layout']
      }
    ])
    export class App {
    }
    
    

    Here is running code: Hope you have fun reading...

    5/11/16

    Routes In Angular2 (Part 1)

    What are Routes?

    Routes are way to access various parts of website using friendly urls. For example if you have a motorcycle store - it will be very convenient if you can navigate to details of page of awesome suzuki GSX1000 using url like:
    mybikestore.com/suzuki/GSX1000

    (instead of using things like:
    mybikestore.com?product=%20%dfgg;ereGSX1000%dfg
    which you have no chance to remember)
    This way the url pretty clear for users and makes much more sense for developers too.
    cannot stop myself from putting here picture of GSX1000 2016

    Routes in Angular2

    Since when talking about angularjs2 we talking about single page application architecture there all the work done by javascript. The routes in angular (both 1. and 2) is the way to load different views (like different pages) of the website. The changes in url triggering javascript event and javascript responds by loading corresponding views, pretty cool isnt it?

    Server

    Speaking about single page application - the idea of single page app is that only one page should be served from the server - so it need to be specially configured.
    Here is configuration of nodejs express server which makes it to serve only index page no matter of what route was chosen.
    
    var express = require('express');
    var app = express();
    app.use(express.static(__dirname));
    
    app.get('/*', function(req, res){
        res.sendFile(__dirname + '/index.html');
    });
    app.listen(process.env.PORT || 3000, function () {
      console.log('Example app listening on port 3000!');
    });
    
    
    

    Routes in angular2

    To implement routes in angular2 'angular2/router' module must be included

    
    import {ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';
    
    
    Also, in the code of main component must present route definitions part - a code which defines the routes and their urls:
    
    @Routes([
      {
        path: '/',
        component: DashboardComponent
      },
      {
        path: '/reports',
        component: ReportsComponent
      }
    ])
    
    
    Notice that in this example we have two views: "Dashboard" and "Reports"

    View

    Like in angular1 - if you want to load routed views in your application you must use the ROUTER DIRECTIVE in the view of the component

    
    import {Component} from 'angular2/core';
    import {ROUTER_DIRECTIVES, Router, Route, RouteConfig} from 'angular2/router';
    ...
    
    @Component({
      selector: 'app',
      template: `
        ...
        <router-outlet></router-outlet>
      `,
      directives: [ROUTER_DIRECTIVES]
    })
    
    

    Here is running code: Hope you have fun reading...

    Getting started with docker

    It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...