Aside

Angular5 part-3

a minimalist quiz component in Angular5 in less than 100 lines of code (including its data).

/> Typescript source

import { Component } from '@angular/core';

@Component({
  selector: 'app-authors',
  templateUrl: './authors.component.html',
  styleUrls: ['./authors.component.css']
})
export class AuthorsComponent {

  // maintains the state of the quiz
  private queId: number = -1;
  private current: number = 0;

  // capture user interaction
  public user: any = {};
  private responses: any = [];

  questions: any = [{
            question: 'Which is the largest country in the world by population?',
            options: ['India', 'USA', 'China', 'Russia'],
            answer: 3
        }, {
            question: 'When did the second world war end?',
            options: ['1945', '1939', '1944', '1942'],
            answer: 1
        }, {
            question: 'Which was the first country to issue paper currency?',
            options: ['USA', 'France', 'Italy', 'China'],
            answer: 4
        }, {
            question: 'Which city hosted the 1996 Summer Olympics?',
            options: ['Atlanta', 'Sydney', 'Athens', 'Beijing'],
            answer: 1
        }, {
            question: 'Who invented telephone?',
            options: ['Albert Einstein', 'Alexander Graham Bell', 'Isaac Newton', 'Marie Curie'],
            answer: 1
        }];

  constructor() {
    this.queId = this.getRandom(0, 4);
    this.user.response = '';
    this.user.score = 0;
    this.user.responses = [];
    this.updateState();
  }

  get isQuizMode() {
      return (this.responses.length <= 4);
  }

  get score(): number {
    return this.user.score;
  }

  onNext() {
    event.preventDefault();
    if (this.current < this.responses.length) {
          this.queId = this.responses[this.current].queId;
          this.user.response = this.responses[this.current].response;
    } else {
          this.responses.push({'response': this.user.response, 'queId': this.queId});
          this.queId = this.getRandom(0, 4);
          this.user.response = '';
    }
    this.updateState();
  }

  onPrev() {
     if (this.current >= 2) {
         if (this.responses.length < this.current) {
             this.responses.push({'response': this.user.response, 'queId': this.queId});
         }
         this.queId = this.responses[this.current - 2].queId;
         this.user.response = this.responses[this.current - 2].response;
         this.current--;
     }// console.log(this.responses);
  }

  updateState (): void {
      if (!this.isQuizMode) {
          for (let i = 0; i < 5; i++) {
              let usrRes = this.responses[i].response;
              let ans = this.questions[this.responses[i].queId].answer;
              if (usrRes == ans) {
                  this.user.score++;
              }
          }
          this.user.score *= 20;
      } else {
          this.current++;
      }
  }

  getRandom(min, max): number {
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

/> The Markup


<!-- render questions //-->
<div *ngIf="isQuizMode; else other_content">
    <form name="frm" #f="ngForm" novalidate>

        <div style="text-align:left">
            {{current}}. {{questions[queId].question}}
            <ul>
                <li>{{questions[queId].options[0]}}</li>
                <li>{{questions[queId].options[1]}}</li>
                <li>{{questions[queId].options[2]}}</li>
                <li>{{questions[queId].options[3]}}</li>
            </ul>
            <input autofocus name="answer" [(ngModel)]="user.response" type="text">
        </div>

        <button type="submit" (click)="onNext()">Next</button>
        <button type="submit" (click)="onPrev()">Prev</button>
    </form>
</div>

<!-- show summary //-->
<ng-template #other_content>
    <h2>Results</h2>
    <h3>Your Score: {{score}}</h3>
        <p *ngFor="let resp of responses; let correct; let i = index;">
            {{i+1}}. queid: {{questions[resp.queId].question}} <br/>
            correct ans: {{questions[resp.queId].answer}}
            user sel: {{resp.response}}<br/>
        </p>
</ng-template>


<br/><br/>

Advertisements

breaking down, package.json

01 | Using Config within package.json

package.json
{
  "name": "npm-labs",
  "version": "1.0.0",
  "description": "",
  "main": "start.js",
  "config": {
    "env": "dev"
  },
  "scripts": {
    "show-conf": "echo env: $npm_package_config_env",
    "first-task": "npm run second-task",
    "second-task": "npm run build --env=$npm_package_config_env",
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "node start.js"
  },
  "author": "hamzeen",
  "license": "ISC"
}
start.js
console.log("name:" + process.env.npm_config_env);

usage:

$ npm run first-task

02 | Passing args to JS file

package.json
{
  "name": "npm-labs",
  "version": "1.0.0",
  "description": "",
  "main": "start.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "node start.js"
  },
  "author": "hamzeen",
  "license": "ISC"
}
start.js
console.log("name:" + process.env.npm_config_name);

usage:

$ npm run build --name=app-name

Angular5 part-2

There is only word which is synonymous with Angular, C H A N G E. Few months ago I made a post on Angular2 & now we have landed on Angular5. It is definitely challenging to keep us on par with the latest in the Angular world.

So to keep my dice rolling, I decided to make my angular posts into a series. In this we look at debugging our unit tests on a browser. In Javascript world, we all know and/or have used Jasmine for Unit Testing at some point.

By default it runs on a headless browser (usually PhantomJS) so we launch the test case/suite from terminal & just wait till test results but we never get to see anything!

But if we change this to a browser like Chrome, we could actually see how the test cases are being executed. Just like UI automation tests, fro example, this would show us text being inserted on forms, button being clicked & etc. Without no more explaination, let’s dive into how we establish this; Just 3 steps!

01 | Get the karma chrome launcher for your project

npm install karma-chrome-launcher --save-dev

02 | Modify karma.conf.json to add the following

    customLaunchers: {
      Chrome_without_security: {
        base: 'Chrome',
        flags: ['--disable-web-security']
      }
    },
    broswers [
        'phantomJS','Chrome', 'Chrome_without_security'
    ]

03 | add the following script definition to package.json

"test-watch": "node node_modules/karma/bin/karma start --browsers=Chrome,Chrome_without_security --single-run=true --auto-watch",

That is it!

Now open up terminal from your project path and hit the following and see magic happen on chrome (look for port on the output)

npm run test-watch

Deploying Node.js app to Heroku


# login to Heroku if not SSH issues!
heroku login

# clone git repo to local drive
git clone git://abc.git

# install packages & build it
cd abc
npm install

# if gitignore found
remove contents of .gitignore

# important creates remote heroku branch & generates a dynamic name for the repo
heroku create
git push heroku master



#after changes
git add .
git commit -m “add local changes”
git push heroic master
heroku open or  heroku open cool

Angular5 part-1

01 | Template on Plunker

https://plnkr.co/edit/gQjnRg?p=info

02 | Setup a project locally using ng-cli

if you already have an older version:

npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli@latest

03 | Configure Routes

WARNING! AppComponent Shouldn’t be part of routing. But it is set as the default route by ng-cli.

> Never Use this:

{ path: '', component: AppComponent },

> Should use something like below:

import { Routes } from '@angular/router';
import { AppComponent } from './';
import { ContactComponent } from './contact/contact.component';
import { AboutComponent } from './about/about.component';

export const routes: Routes = [
  { path: '', redirectTo: '/contact', pathMatch: 'full' },
  { path: 'contact',  component: ContactComponent },
  { path: 'about',  component: AboutComponent },
  { path: '**', redirectTo: '/contact', pathMatch: 'full' },
];
Route Redirection: 
  { path: '**', redirectTo: '/contact', pathMatch: 'full' },
Wildcard Routes: 
  { path: '**', component: PageNotFoundComponent },

04 | Routing

From Template:

<a [routerLink]="['/signup']">Click here to Signup</a>

From your .ts file (typescript):

// src/app/landing/landing.component.ts
import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent {
  title = 'landing page';
  constructor(private router: Router) {}

  launchHome(): void {
    this.router.navigate(['/home']);
  }
}

05 | Barrel Files for the rescue

One of the first things you will notice when you start working on it is, you have to write so many import statements. Gets worst, when you have to make 2 dedicated imports to get hold of 2 components sitting inside the same folder.

Well, this isn’t one of those where you blame at Angular! This is something to do with Typescript. The resolution is to use barrel files. As a practice you can start creating an index.ts file in each of your folders containing services, components or feature modules.

Assume you src folder has too many components (example: Home, About, Contact):

The barrel file:

// src/app/index.ts
export { AppComponent } from './app.component';
export { HomeComponent } from './home.component';
export { AboutComponent } from './about.component';
export { ContactComponent } from './contact.component';

Usage:

import { AppComponent, HomeComponent, AboutComponent, ContactComponent} form './';

// or even simpler
import { * } from './';

There is a neat blog on this which can give you a better understanding of this.

06 | Running the App

ng serve

and navigate your browser to http://localhost:4200

07 | Unit Test and other CI/CD Concerns

There are scripts setup on package.json for these, one can refer it. For more on configuring karma & etc read this blog. Example, Running unit tests (jasmine – BDD):

ng test

08 | Need to create your feature module?

After sometime you realize your app module has grown out of proportion. It is time to consider some logical organization of your code. First is to consider organizing them into modules. Here is a neat read

09 | Adding a Simple Form

You will notice I’ve placed a simple form in ContactComponent. At this point it’s important that you don’t forget to import FormsModule in your app.module.ts.

However, one thing you will notice there is a realtime representation of form data. It is quite useful for you to debug, it can be achieved with the following peace of markup:


    <form #form="ngForm">
      ...
    </form>

    <div>Formdata in realtime:
      <pre>{{ form.value | json }}</pre>
    </div>

10 | Lifecycle Hooks

Intention behind post was to have an Angular2 guide which would help one to start a project from scratch & take it all way to deployment. I haven’t covered much of Angular2 concepts or structs on this post for brevity & aligning with my intention to keep it super short. However, Lifecycle Hooks are a thing it can’t afford to miss. Angular2 provides 8 of them in total: ngOnInit, ngOnChanges, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy. Here is an example:

import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
  constructor() {}

  ngOnInit() {
    console.log('App Component Init');
  }

  ngOnDestroy() {
    console.log('App Component Destroyed');
  }
}

You can refer this blog if you want to know them in detail

11 | Before you go for Production

You are just a command away if you want to do a production build for your awesome app. Afterwards you just need to copy the generated dist folder to your live server.

ng build --aot --environment prod

Yet, there are few things one should know going to this step. When you execute above the step there are so many things happening behind the scene. Here are some, concatenation, minification, uglification & tree shaking.

Since I have already made a note on first 3 on a different blog, I would like you to come to terms with Tree Shaking.

Tree Shaking is the process of getting rid of dead code. If you’re coming from Java world or most other OOP environments, you will be familiar with a warning called ‘unused code/method’. However, if you want to go deep into it with examples & numbers here is great post from an expert. Minko Gechev is the author of the official Angular Style Guide.

If you are already an expert at Angular & came across this post whilst considering ways to improve the page load time & performance tuning for your app here is a great stack overflow thread which you shouldn’t miss!

12 | Sourcecode

Here is the github repo used for this post.

filter component

1. All urls to 1 route

Router.map(function() {
  this.route('about', {path: '/'});
  this.route('about', { path: '/*wildcard' });
});

2. Dom Manipulation

// in any controller
Ember.$('#component-x').val('My Value');

3. Adapter: rental.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  'namespace': 'api'
});

4. Template: index.hbs

<div class="jumbo">
  <div class="right tomster"></div>
  <h2>Welcome!</h2>
  <p>
    We hope you find exactly what you're looking for in a place to stay.
    <br>Browse our listings, or use the search box above to narrow your search.
  </p>
</div>

{{input value=filterText type='text' placeholder='Search City'}}
  {{#unless filteredResults.length}}
    <h4>no record matched your criteria</h4>
  {{/unless}}

  <ul>
    {{#each filteredResults as |item|}}
      <li>{{item.id}} {{item.attributes.city}}</li>
    {{/each}}
  </ul>

5. Route: index.js

import Ember from 'ember';

export default Ember.Route.extend({
  filterText: '',

  setupController(controller, model) {
    this._super(controller, model);
    controller.set('filterText', this.get('filterText'));
  },

  queryParams: {
    search: {
      refreshModel: true
    }
  },

  beforeModel: function(transition) {
    // console.log('before model: '+transition.queryParams.search);
    this.set('filterText', transition.queryParams.search);
  },

  model: function(params) {
    var endPoint = 'http://localhost:4200/api/deals';
    var results = [];

    endPoint = (params.search)? endPoint+'/city='+params.search : endPoint;

    $.ajax({
      url: endPoint,
      type: 'GET',
      accepts: 'application/json',
      success: function(data) {
        if(data.rentals) {
          data.rentals.forEach(function(deal) {
            results.addObject(deal);
          });
        } else if(data.data === 'no records found'){
          console.log('No results found');
        } else {
          data.data.forEach(function(deal) {
            results.addObject(deal);
          });
        }
      },
      error: function() {
          console.log('DEBUG: GET Deals Failed');
      },async:false
    });
    return results;
  }
});

6. Controller: index.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['search'],

  onFilterTextChange: function() {
    Ember.run.debounce(this, this.applyFilter, 0);
  }.observes('filterText'),

  applyFilter: function() {
    this.set('search', this.get('filterText'));
    console.log('search set: ' + this.get('search'));
  },
  
  filteredResults: function() {
    return this.get('model');
  }.property('search'),
});

7. Mock Response(http-mock): rentals.js

/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var rentalsRouter = express.Router();
  var rentals = [
      {
        type: 'rentals',
        id: 1,
        attributes: {
          title: 'Grand Old Mansion',
          owner: 'Veruca Salt',
          city: 'San Francisco',
          type: 'Estate',
          bedrooms: 15,
          image: 'https://upload.wikimedia.org/wikipedia/commons/c/cb/Crane_estate_(5).jpg'
        }
      }, {
        type: 'rentals',
        id: 2,
        attributes: {
          title: 'Urban Living',
          owner: 'Mike Teavee',
          city: 'Seattle',
          type: 'Condo',
          bedrooms: 1,
          image: 'https://upload.wikimedia.org/wikipedia/commons/0/0e/Alfonso_13_Highrise_Tegucigalpa.jpg'
        }
      }, {
        type: 'rentals',
        id: 3,
        attributes: {
          title: 'Downtown Charm',
          owner: 'Violet Beauregarde',
          city: 'Portland',
          type: 'Apartment',
          bedrooms: 3,
          image: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Wheeldon_Apartment_Building_-_Portland_Oregon.jpg'
        }
      }
    ];

  rentalsRouter.get('/', function(req, res) {
    res.send({
      rentals
    });
  });


  rentalsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  /*rentalsRouter.get('/:id', function(req, res) {
    res.send({
      '':req.params
    });
  });*/

  rentalsRouter.get('/:city', function(req, res) {
    let val = req.params.city.split("=");
    let filteredRentals = rentals.filter(function(i) {
      return i.attributes.city.toLowerCase().indexOf(val[1].toLowerCase()) !== -1;
    });

    if(filteredRentals.length>=1) {
      res.send({
        'data': filteredRentals
      });
    } else {
      res.send({
        'data': 'no records found'
      });
    }

    
  });

  rentalsRouter.put('/:id', function(req, res) {
    res.send({
      'rentals': {
        id: req.params.id
      }
    });
  });

  rentalsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:

  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //
  //app.use('/api/rentals', require('body-parser').json());
  app.use('/api/rentals', rentalsRouter);
};

Journal – publish bower package; setup ember mock

1. Publish Bower Package

Bower was started by twitter.
https://bower.io/docs/creating-packages/

2. Simple Ember App

Super Rentals

3. Mocks with EmberJS

EmberJS comes with ExpressJS (internally, http-mock) here are steps to setup a mock. Once setup it works like a real service & it actually be used to build REST API for your backend if it is fueled with real data.

  • generate ember project with ember-cli
  • generate an express route
    ember g http-mock destinations
  • to view: http://localhost:4200/api/destinations
  • Unlike fixtures, this helps you test your Adapter as well
  • setting up a mock response
// server/mocks/destinations.js
/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var destinationsRouter = express.Router();

  destinationsRouter.get('/', function(req, res) {
    res.send({
      'destinations': [
		{
			id:'001',
			loc: 'london'
		}, {
			id:'002', 
			loc: 'rotterdam'
		}, {
			id:'003', 
			loc: 'amsterdam'
		}
	  ]
    });
  });

  destinationsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  destinationsRouter.get('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.put('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:
  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //app.use('/api/destinations', require('body-parser').json());
  app.use('/api/destinations', destinationsRouter);
};