json - Angularjs $resource and $http synchronous call? -
i want write 2 services 1 $http.get
method , 1 $resource
this service should receive json object , looks this, @ moment code direct in controller , not in service:
var csvpromise= $http.get(base_url + 'datasource/1').success(function(data) { $scope.data4=json.stringify(data); });
the problem is, want save received data in $scope.data4
, want use data after $http.get
call value empty.
direct after call there , object needs value:
new myobject($scope.data4)
so myobject
must wait long until data has arrived.
or can make synchronous call $http
or $resource
?
how can ? have found many examples promise
, .then
nothing has worked me.
edit: have written service didn`t work:
var test=angular.module('myapp.getcsv', ['ngresource']); test.factory('getcsv',function($log, $http,$q, $resource){ return { getdata: function (id) { var csvpromise= $http.get(base_url +'datasource/'+id) .success(function(data) { return data; }); return csvpromise; } } });
and in controller call this:
getcsv.getdata(1).then(function(thedata){ $scope.data4=json.stringify(thedata); new myobject( $scope.data4); });
but did not work. thought if $http.get
receives data then
function called.
i don't believe can synchronous calls. said, have @ least 2 options:
1) pass in data using $routeprovider
resolve
feature. documentation:
an optional map of dependencies should injected controller. if of these dependencies promises, router wait them resolved or 1 rejected before controller instantiated. if promises resolved successfully, values of resolved promises injected
an example on how use this:
$routeprovider .when('/your/path', { templateurl: '/app/yourtemplate.html', controller: 'yourcontroller', resolve: { data: ['$route', '$http', function($route, $http) { return $http.get(base_url +'datasource/1'); }] } })
and in controller:
app.controller('yourcontroller', ['$scope', 'data', function($scope, data) { $scope.data4 = json.stringufy(data); var yourobj = new myobject($scope.data4); }]);
2) second option use promises , instantiate new myobject($scope.data4)
once promise completes.
Comments
Post a Comment