Friday 22 May 2015

Angular 2 -How to make Ajax call with Custom Service



I have been playing with Angular 2 to make ajax calls.But the Angular Quick-start does not have any documentation for $http module used as of Angular 1x. After googling , found out the answer, that Angular 2.0 DOES NOT have a $http service

1.Angluar JS has a separate data persistence layer, that will cover HTTP. This is not finished yet.
2.Because of Zone in Angular 2 you can use any existing mechanism for fetching data. This includes XMLHttpRequest fetch() and any other third party libraries.
3.XHR in the compiler is meant to be private, and should not be used.
 So the solution will be,
Create a factory class which acts as a wrapper and hold all the methods for HTTP requests.
  export const $http = {
	get: function(url: string) {
		return _sendRequest(url, null, 'GET');
    },
    post: function(url: string, payload: any){
    	return _sendRequest(url, payload, 'POST');
    },
    put: function(url: string, payload: any){
    	return _sendRequest(url, payload, 'PUT');
    },
    delete: function(url: string, payload: any){
    	return _sendRequest(url, null, 'DELETE');
    }
}
Use XMLHttpRequest for making the actual Ajax calls and return a Angular Promise.
    function _sendRequest(url: string, payLoad: any, type: string): Promise {
        return new Promise(function(resolve, reject) {
            var req = new XMLHttpRequest();
            req.open(type, url);
            req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

            if (payLoad) {
                req.send(JSON.stringify(payLoad));
            } else {
                req.send(null);
            }
        });
    }
Handle the JSON parsing in the "resolve" callback and error handling in the "reject" callback.
    function _sendRequest(url: string, payLoad: any, type: string): Promise {
        return new Promise(function(resolve, reject) {
            var req = new XMLHttpRequest();
            req.open(type, url);
            req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

            req.onload = function() {
                if (req.status == 200) {
                    resolve(JSON.parse(req.response));
                } else {
                    reject(JSON.parse(req.response));
                }
            };

            req.onerror = function() {
                reject(JSON.parse(req.response));
            };

            if (payLoad) {
                req.send(JSON.stringify(payLoad));
            } else {
                req.send(null);
            }
        });
    }
Register a "then" callback for the Promise returned and set the view objects for rendering them to the template
   $http.get('http://jsonplaceholder.typicode.com/posts?userId=1').then(function(json) {
         appClass.greetings = json;
      });

Example plunkr




Tuesday 19 May 2015

AngularJS 2.0 - What's new? My Take

Before u Start:

Read the following to get insight on specifications over which the AngularJS 2.0 is built.

1.Angular JS is written in ES6. Simple explanation of ES6 features can be read from here.
2.Angular JS uses AtScript(@ script) - Angular's Extension of ES6 features to support annotations & decorators similar to annotations in Java.
3.Angular JS uses traceur transpiler. It allows the new and proposed future EcmaScript features to be used in browsers.
4.es6-shim.js - To add ES6 in current browsers. 

Annotations:

AtScript provides 3 types of annotations - Type Annotations, Field Annotations and MetaData Annotations.
Lets start for now with, 

             1.@Component - Indicates the class is a component
             2.@View- As the name suggests-it is the view of the component.It can be a HTML template.They add some meta data to the class in order to give it a specific meaning. They are a declarative way to add meta data to code.

How to create a Angular 2.0 Component?

Angular 2 works with a concept of components. Each component consist of 2 parts
  1. The Annotation Section(@Component & @View) – This consist of the meta data (component selector, template) for that component
  2. The Component Controller Section(Class) – This is a ES6 Class, from which the template would be reading the properties that are interpolated ({{…}}) inside it .

   import {  ComponentAnnotation as Component,
  ViewAnnotation as View,bootstrap} from 'angular2/angular2';

  @Component({
  selector: 'app'
  })
  @View({
    template: 'Hello {{ name }}'
   })
  class App{
    constructor() {
     this.name = 'Muthu!';
    }
  }
   bootstrap(App);
Example plunkr