function HttpService(tokenService){ this.tokenService = tokenService; } HttpService.createInstance = function(tokenService){ var tokenService = tokenService || new TokenService(); return new HttpService(tokenService); } HttpService.prototype = { _send : function(cfg){ var self = this; return new Promise(function(resolve,reject){ cfg.beforeSend = function(request) { if ( self.tokenService.hasToken() ) { var token = self.tokenService.getToken(); request.setRequestHeader("x-access-token", token); } }; $.ajax(cfg).fail(reject).done(resolve); }) }, get : function(url,dataType){ return this._send({ dataType: dataType || 'json', contentType: 'application/json', url: url, type: 'GET', }); }, delete : function(url){ return this._send({ dataType: 'json', url: url, type: 'DELETE', }); }, post : function(url,dados){ return this._send({ dataType: 'json', contentType: 'application/json', url: url, type: 'POST', data:JSON.stringify(dados), }); }, put : function(url,dados){ return this._send({ dataType: 'json', url: url, type: 'PUT', data:JSON.stringify(dados), }); } };