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




No comments:

Post a comment