promise - AngularJS: Creating a $http service -
i'm little new angular, , i'm trying set simple rpc implementation uses angulars $http
service (factory) work. here's have service far:
'use strict'; angular.module('xxx') .factory('rpcservice', function ($http) { return { request: function(method, params, callback) { var service = method.split('.'); params = params || {}; params.method = service[1]; return $http.post('/services/' + service[0] + '.sjs', params).then(function (response) { return response.data; }); } } });
then when want use service, call following:
rpcservice.request('users.facebooklogin', { token: response.authresponse.accesstoken }) .then(function(response) { debugger; $rootscope.user = response.user; console.log($rootscope.user); $rootscope.loggedin = true; $rootscope.$apply(); });
the code never gets lines after debugger; in fact, code never makes $http
request @ all. reason stops , doesn't continue callback...or promise...i'm bit confused technical difference is. :)
that being said, i've tested post call $.ajax
, returns properly, off angular code.
and code fires request , work $.ajax
:
'use strict'; angular.module('xxx') .factory('rpcservice', function ($http) { return { request: function (method, params, callback) { var service = method.split('.'); params = params || {}; params.method = service[1]; $.ajax('/services/' + service[0] + '.sjs', { type: 'post', datatype: 'json', data: params, success: function(data, status, xhr) { if (callback) { callback(data); } } }); } } });
i'm unsure why xhr request isn't being made.
the api call may error callback never triggered. try add error()
callback this:
return $http("post", '/services/' + service[0] + '.sjs', params) .error(function (response) { return 'blah'; }).then(function (response) { return response.data; });
you can try on demo. code looks good.
Comments
Post a Comment