Showing posts with label angularjs. Show all posts
Showing posts with label angularjs. Show all posts

Wednesday, August 9, 2017

Angular  —  Exception Handling Mechanism

One of the main issue which i came across with angular  was exception handling.  When you are developing an application, you are in full control, and you will be able to see the errors and handle them accordingly.
But as you soon deploy it in the production,  you can’t see what your user is seeing and experiencing and you not capable of knowing about errors unless you find a way to be notified about the exceptions.
This solution i have implemented recently and it worked pretty well. Angular 2 has his own way to catch and handle errors. The default implementation of ErrorHandler prints errors messages to the console. You can intercept the default error handling and write a custom exception handler that replaces this default as appropriate for your app.
If you have a production server and you want to send the errors to the server, Let’s see how we can do it.

you need to create your own ErrorHandler class that implements the default ErrorHandler. The only method that required is the handleError method that takes the error as an argument.

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  
   }  
 }  


The next step you can go is to change your injector to use your implementation instead of the default. So code will be something like this,

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  
   }  
 }  

That’s all folks. If you don’t want to ignore the Angular default handler, you can extend the ErrorHandler class and also call the default handler like this:

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  
   }  
 }  

That's it guys!. You can apply this method on your application and make it error free on production. 
You can check the sample on plunker and play with it!

Friday, January 27, 2017

Shift from Angular1 to Angular2 if you are an Angular 1.x fan

I am a big fan of AngularJS over the years and involved in developing enterprise applications using Angular1. To all the angular1.x developers out there, am going to write about my experience on migrating from Angular 1.x to Angular 2.

Let's find out the differences ,

(i) To those who think Angular2 is the updated version of Angular1, No it is not . Only the names are same,  Angular 2 is completely rewritten.



(ii) Angular1 is using javascript whereas Angular 2 is using Typescript which is super set of javascript



(iii) Most of us are familiar with the $scope in Angular1, one core concept was $scope, and you the saddest part is we don't find $scope in angular 2. Angular 2 use  zone.js to detect changes.



(iv) If you are a mobile developer Angular1.x does not provide much, where Angular 2 is mobile oriented.



(v) Angular 1.x use controllers to handle the logic part, which are gone. And  controllers are replaced with “Components” in Angular 2.


////Angular 1.x using Controller and $scope.........
var myApp = angular .module("myModule", [])
var prods = { name: "Prod1", quantity: 1 };
.controller("productController", function($scope) { $scope.products = prods;
});
///Angular 2 Components using TypeScript........
import { Component } from ‘angular2/core’;
template: `{{prods.name}}`
@Component({ selector: ‘prodsdata’, })
prods = { name: ‘Prod1’, quantity: 1 };
export class ProductComponent {
}

(vi) One of the favourite directive for generating elements was ng-repeat with Angular 1.x
ng-repeat is replaced with *ngFor.
///Angular 1.x structural directives:........
<ul>
{{item.name}}
<li ng-repeat="item in items">
///Angular 2 structural directives:.............
</li> </ul> <ul>
{{item.name}}
<li *ngFor="#item of items"> </li>
</ul>

(vii) Declaring the local variables also changed with angular2  using hash(#) prefix.


(viii) Even though most of the concepts remains the same Two-way data binding: ng-model replaced with [(ngModel)] in angular 2.


(ix) Concept of bootstraping has changed too.Angular 1.x has 2 ways to bootstrap angular. One using ng-appattribute and other via code. In Angular 2, The only way to bootstrap angular is via code.
 import { bootstrap } from 'angular2/platform/browser';  
 import { ProductComponent } from './product.component';  
 bootstrap(ProductComponent);  


(x) Apart from all the above, main concepts such as ways of Routing and Depdency injects has been changed drastically with angular2.


In Angular 1.x, we use $routeProvider.when() to configuring routing. Where in Angular 2, @RouteConfig{(...}) is used. ng-view present in Angular 1.x is replaced with


One of the advantages of Angular1 Dependency Injection. In angular 2 everything is ‘class’ , so DI is achieved via constructors.


To begin with Angular 1.x you should be well versed with java script. Angular 1.x is simpler and easy to learn/coding based on Javascript, whereas Angular 2 just got released LIVE version and it is easy for Java developers to grasp the concepts of Angular 2.To begin with Angular 2 first start with the basic concepts of AngularJS to understand things in Angular 2 better. Happy Learning!


Tuesday, November 8, 2016

Angular Directives with D3

It's been exactly 2 years since i started to learn Angular and it's sad that i dint write even a single blog on the same. Finally decided to start a series on the same topic. AngularJS is a JavaScript MVC Framework that integrates two-way data binding, web services, and build web components. There are enough number of blogs and tutorials to follow on the same.

The current product which i am working is a data visualization tool which is built on AngularJS  and has many visualization  been integrated with D3.js.

In this blog, will be describing how to build a directive using d3.js and angular.

Directive is very powerful feature of AngularJS. It easily wired up with controller, html and do the DOM manipulations.

Building a Decomposition Force directed d3 directive:


 App.directive('forceGraph', function() {  
   return {  
     restrict: 'EA',  
     transclude: true,  
     scope: {  
       chartData: '='  
     },  
     controller: 'hierarchySummaryCtrl',  
     link: function(scope, elem, attrs) {  
       var svg;  
       elem.bind("onmouseover", function(event) {  
         scope.svg = svg;  
         console.log("hierarchy svg", scope.svg);  
         scope.$apply();  
       });  
       scope.$watch('chartData', function(newValue, oldValue) {  
         if (newValue) {  
           scope.draw(newValue.data,newValue.id);  
         }  
       });  
       scope.draw = function(rootData,divID) {  
         var width = 400,  
           height = 320,  
           root;  
         var force = d3.layout.force()  
           .linkDistance(80)  
           .charge(-120)  
           .gravity(.05)  
           .size([width, height])  
           .on("tick", tick);  
         var divid = "#" + divID;  
         d3.select(divid).selectAll("*").remove();  
         svg = d3.select(divid)  
           .append("svg").attr("viewBox", "0 0 400 400")  
           .attr("width", '100%')  
           .attr("height", '100%');  
         var link = svg.selectAll(".link"),  
           node = svg.selectAll(".node");  
         root = rootData;  
         update();  
         console.log(svg);  
         scope.setSvg(svg[0][0].innerHTML);        
         function update() {  
           console.log(nodes)  
           var nodes = flatten(root),           
           links = d3.layout.tree().links(nodes);          
           var nodes = flatten(rootData),           
           links = d3.layout.tree().links(nodes);             
           force.nodes(nodes)  
             .links(links)  
             .start();  
           // Update links.  
           link = link.data(links, function(d) {  
             return d.target.id;  
           });  
           link.exit().remove();  
           link.enter().insert("line", ".node")  
             .attr("class", "link");  
           // Update nodes.  
           node = node.data(nodes, function(d) {  
             return d.id;  
           });  
           node.exit().remove();  
           var nodeEnter = node.enter().append("g")  
             .attr("class", "node")  
             .on("click", click)  
             .call(force.drag);  
           nodeEnter.append("circle")  
             .attr("r", function(d) {  
               return Math.sqrt(d.size) / 5 || 4.5;  
             });  
           nodeEnter.append("text")  
             .attr("dy", ".25em")  
             .text(function(d) {  
               return d.name + ", Count: " + d.size;  
             });  
           node.select("circle")  
             .style("fill", color);  
         }  
         function tick() {  
           link.attr("x1", function(d) {  
               return d.source.x;  
             })  
             .attr("y1", function(d) {  
               return d.source.y;  
             })  
             .attr("x2", function(d) {  
               return d.target.x;  
             })  
             .attr("y2", function(d) {  
               return d.target.y;  
             });  
           node.attr("transform", function(d) {  
             return "translate(" + d.x + "," + d.y + ")";  
           });  
         }  
         function color(d) {  
           return d._children ? "#FFEB3B" // collapsed package  
             :  
             d.children ? "#F44336" // expanded package  
             :  
             "#D32F2F"; // leaf node  
         }  
         // Toggle children on click.  
         function click(d) {  
           if (d3.event.defaultPrevented) return; // ignore drag  
           if (d.children) {  
             d._children = d.children;  
             d.children = null;  
           } else {  
             d.children = d._children;  
             d._children = null;  
           }  
           update();  
         }  
         // Returns a list of all nodes under the root.  
         function flatten(root) {  
           var nodes = [],  
             i = 0;  
           function recurse(node) {  
             if (node.children) node.children.forEach(recurse);  
             if (!node.id) node.id = ++i;  
             nodes.push(node);  
           }  
           recurse(root);  
           return nodes;  
         }  
       };  
     }  
   };  
 });  
My Repository With the sample