Angular2

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.

Advertisements

Javascript

Lempel–Ziv–Welch (LZW) Compression in JS

// Decode LZW-encoded string
function lzwDecode(s) {
        var dict = {};
        var data = (s + "").split("");
        var currChar = data[0];
        var oldPhrase = currChar;
        var out = [currChar];
        var code = 256;
        var phrase;
        for (var i = 1; i < data.length; i++) {
            var currCode = data[i].charCodeAt(0);
            if (currCode < 256) {
                phrase = data[i];
            }
            else {
                phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
            }
            out.push(phrase);
            currChar = phrase.charAt(0);
            dict = oldPhrase + currChar;
            code++;
            oldPhrase = phrase;
        }
        return out.join("");
}

// Compress a string with LZW
function lzwEncode(s) {
        var dict = {};
        var data = (s + "").split("");
        var out = [];
        var currChar;
        var phrase = data[0];
        var code = 256;
        var i, l;
        for (i = 1, l = data.length; i < l; i++) {
            currChar = data[i];
            if (dict[phrase + currChar] != null) {
                phrase += currChar;
            }
            else {
                out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
                dict[phrase + currChar] = code;
                code++;
                phrase = currChar;
            }
        }
        out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
        for (i = 0, l = out.length; i < l; i++) {
            out[i] = String.fromCharCode(out[i]);
        }
        return out.join("");
}
Image

JSON

JS Var to JSON & vice-versa

function getObj() {
  var arrA = [22,43], arrB = [];
  return {
   ar1:arrA, 
   ar2:arrB
  };
}
var arr = getObj().ar1;
console.log(arr);

var arr1 = [1,2];
var arr2 = [3,4];

var obj = {a:arr1,b:arr2};

console.log(JSON.stringify(obj)); // {"a":[1,2],"b":[3,4]}
console.log(JSON.stringify(arr2)); // [3,4]

// adding top node to existing obj
var withPref = {'pref' : obj}

console.log(JSON.stringify(withPref)); // {"pref": {"a":[1,2], "b":[3,4]} }

var arr = (obj.a).concat(obj.b);
console.log(arr); // plain js array: [1, 2, 3, 4]

var jane = {"person":[{"id":121},{"title":"Jane"}]};

All About JSON Manipulation

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
	<style>
	html,body {
		margin: 5px 0px 0px 5px;
		padding: 10px 0px 0px 0px;
	}
	span {
		border-radius: 3px;
		background: #220;
		color: #fff;
		padding: 10px;
	}
	</style>
  </head>

  <body>
    <div class="content"></div>
    <script src='jquery3.1.1.js'></script>

	<script type="text/javascript">
	$( "div.content" ).html("<span>Hello Again! I will exapnd</span>");
	$( "div.content span" ).append("&nbsp; > ABC" );
	
	var arry1 = [];
	var temp = {
		"gpc": [
          {
            "top": "Top1",
            "gmp": [
              {"name": "1. Basic Acc Srv"},
              {"name": "jquery"},
              {"name": "json"}
            ]
          },
			    {
            "top": "Top2",
            "gmp": [
              {"name": "1. Basic Acc Srv"},
              {"name": "ember"},
              {"name": "Top1"}
            ]
          }
		]
	};

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));    
        } else 
        //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
        if (i == key && obj[i] == val || i == key && val == '') { //
            objects.push(obj);
        } else if (obj[i] == val && key == ''){
            //only add if the object is not already in the array
            if (objects.lastIndexOf(obj) == -1){
                objects.push(obj);
            }
        }
    }
    return objects;
}

function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}

function getKeys(obj, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
			objects = objects.concat(getKeys(obj[i], val));
        } else if (obj[i] == val) {
			objects.push(i);
        }
    }
    return objects;
}


// then to get the JSON string
if(arry1.length === 0) {
  // console.log("empty arry");
} else {
  var strJSON = JSON.stringify({gpc: arry1});
  // console.log('New::: \n'+strJSON );
}

// console.log('Org::: \n'+JSON.stringify(temp));
var obj1 = getObjects(temp,'top','Top1');
var obj2 = getObjects(temp,'top','Top2');

var main = obj1.concat(obj2);

console.log(JSON.stringify(main));
	</script>
  </body>

</html>

adding a parent node

Stack Answer

Concat

Pen

See the Pen parse json by Hamzeen H (@hamzeen) on CodePen.

https://production-assets.codepen.io/assets/embed/ei.js

JSFiddle

http://jsfiddle.net/hamzeen/dw3q67md/

Back with Flock-The Social Web Browser

Guys Lonely Coder is back after a week of heavy work with a freaking project for Cutting Edge which is the most exiting event of IIT every year, Where the Final years of IIT enterprise their talent on stage to the public. And this is where all the work that they put over the years at IIT get exposed to the industry what we are really capable of being, students of University of Westminster. This time for this ever so  fascinating event, second years are also invited to take part due to lack of projects & gues what Lonely Coder grabbed it with both hands.

The project of us APES which stands for Automated Police Entry System. It’s  another entreating project I have come across after the long lasting nights working out on  Successlands another devastating project at Archmage which took me months to work on and believe me still it is incomplete. You can have a look at it via,

SuccessLands.com

Today I get a chance to explore a few breathtaking features of my new browser, should say a social web browser to be precise. Namely it’s Flock. Believe me this post is actually written & published right from the Flock browser how that sounds for a blogger… I’m sure already the guys must be pumped up to figure out how this actually works. It’s really easy as giving your particular blog’s username & password, don’t worry what ever the sort of blogger you are it supports all the famous blogs like blogger, wordpress in my case, xanga, LiveJournal, TypePad and many more.

This is just another single amazing aspect of Flock. You got many more than this , to start  with one might wonder if it another version of firefox if you were firefox browser over the years. Yes it looks very similar to firefox and also uses the same technology for fast browsing.

Going through few of the other embarasing features of Flock,

  • Favorites management
  • Feed reader
  • Media minibar
  • Photo Uploader
  • Account Handling
  • Again Flock’s in-built Photo uploader also provides support to uploading media to most of your media sites which includes PICZO, Flickr, YOUTUBE & Photo Bucket. Never worry with signins just goto your browser and get access to most of your favourite sites. Nothing to type in your addressbar unless you wanna discover a new site.

    With all these wonderfull integerations it provides one with instantaneous access to most of their favourite sites. But then again security wise it’s really dangerous to leave your account informations in the browser so in that case Flock becomes an extremely confidential and a private browser.

    If you are interested in trying out Flock visit,
    Flock.com

    Blogged with Flock

    T20 World Cup -Where the Drama Begins

    Yesterday (2nd day of ICC twenty-twenty inaugural World Cup) Zimbabwe met The three times consecutive world cup winners Australia in another thrilling encounter.

    The minors(Zimbabwe) played good positive cricket wright from the beginning were paid of for their effort in the field and aussies were all over the place with Sky Scrapers most of them got caught in the deep. The drama continued and Aussies were restricted down to 138 for 9 wickets.

    Later in the evening Zimbabwe chased it down to welcome Aussies to ICC T20 WorldCup with a Shock Treatment.

    Earlier KIWI’s (New Zealand) marked their arrival to the WorldCup with a comprehensive win over Kenya.

    And Pakistan too marked their first victory in the T20 World Cup win with a much fought win over Scotland after they were restricted by the underdogs (Scotland) for a mere 171 for the loss of 9 wickets.

    Many Cricket Critics are still reluctant to express their view over this new innovation by the ICC and it will remain so up untill the end of this fascinating tournament as the Drama continues.

    Happy Blog Day

    Today, august 31st happens to be the third annual Blog Day, to join the celebrations all the bloggers are being asked to find five new blogs that you find interesting and notify them that you are recommending them in order to celebrate the event and also to give a brief description of those blogs in your blog.

    Blog Day 2007

    PC & Mobile Phone can they Co-Exist ?

    Whenever I receive a call or a text message on ma hand phone it seem to have disturb my PC’s both monitor and speaker a great deal. Hence this week I thought of going a bit into Physics.

    We all know that electric conductors when they are conducting electricity will have a magnetic effect on them, a good example is when you place a nail near an electric conductor(Say a Wire) while conduction will attract the nail towards it.

    Actually current is produced owing to the movment electrons (technically this is called a change in electric field), the direction of the induced current will always be in the opposing direction

    not stopping there the conductor will also producing a manetic field around it and electrons will be moving towards the north pole of the conductor. Now it is said to produce an Electro Magnetic Field (E-M). which is a combination of both electric and magnetic field at the same time. This energy is same as any other form of energy can do work. And the work dine is given by,

    ∆W=F∆S
    where W is notationed for Work, F for Force and S for displacement

    This is where we can apply Flemming’s left hand rule figure ouit the direction the Force produced during this event.

    Direction of induced Force

    All these research I carried out to figure out my particular problem which is also due electro-magnetic waves, it is called the Electro Magnetic Interference (EMI).

    Why monitor responds first?

    intersting part of my particular scenario is that I get a trigger in my monitor even before I hear the ring tone or my speaker gets disturbed.
    When I digg deap into this particular case what I find is very simple, it is because light waves are faster than sound waves.
    Acording to,
    v= fλ

    Where v represents velocity, f represents frequrncy, and λ for wave length.
    according to this relationship you can see that frequency(f) is inversely propotional to wavelenth(λ) as weell.
    hence smaller the wavelength, higher the frequency whilst the velocity remains constant.but,
    f=1/t

    this would suggest when higher the frequency lower the time it take s to travel. And that’s it. When you take the spectrum you will find that light wave’s wavelength is lower than sound waves. this the perfect reason for this matter. This is the reason that I could find for my monitor to respond first.

    Why Electro-Magnetic waves are so dominent?

    The other importatnt fact about Electromagnetic waves is that it is so quick to travel and they do not need any medium to travel they travel through vaccum as well, not like Sound waves or some other waves hence this is the way that rays from sun travel to earth in the space where there is no air.

    But after all these researches what Lonely Coder has to say is that there is no stable solution to overcome this senario. But stll I could findcarrying out some serious reaserches, hope they would be paid for their there effort.