Return object from AngularJS $ http get

I use the following code to get a json object and bind it to $ scope

WORKING CODE:

$http({ url: '/Home/GetJson', method: "GET", params: { clientID: cId } }).success(function (data) { $scope.members = data.members; }) 

This works .. what I would like to do is get the results in var data , and then add it to the $ scope.

FAULT CODE:

 var data = $http({ url: '/Home/GetJson', method: "GET", params: { clientID: cId } }).success(function (data) { return data.members; }) $scope.members = data; 

When I look at $ scope.members, it is empty in error codes because $ scope.members is empty when it is full (js is an event).

How can I wait until json returns> then var = data> and then $ scope.members = data?

WORK CODE

I used Javascript callback functions as below

Call my main function

 DoLogin($scope, $http, email, password, AssingMemberToScope); function DoLogin($scope, $http, email, password, callback) { $http({ url: '/Home/GetJson', method: "GET", params: { clientID: cId } }).success(function (data) { callback($scope, data); //<----- Call Back occurs }) } 

// - Callback function and code are separated - /

 function AssingMemberToScope($scope, data) { if (data.msg) { $('.loading').hide(); $scope.member = data.member; } else { $('.loading').hide(); $('#msg').show(); } } 
+6
source share
3 answers

I think the best approach would be to include a JSON call in a function that takes a callback function as a parameter. Quick example:

 function makeJSONCall(callback) { $http({ url: '/Home/GetJson', method: "GET", params: { clientID: cId } }).success(function (data) { callback(data); }); } function someFunctionCallback(param) { console.log(param) } 

Now, inside this callback function, do what you want with the data. You can also call the JSON function when you need it now, just makeJSONCall(someFunctionCallback) .

+7
source

Try this template:

 angular.module('App').factory('service', function ($http) { var service = { myFunction: function (query) { var promise = $http({ url: '/Home/GetJson', method: "GET", params: { clientID: cId } }).success(function (data) { return data.members; }); return promise; }; } }); 

Then when you consume the service, do

 service.myFunction(query).then(function (data) { $scope.members = data.members; }); 
+8
source

In fact, you explained this in your last sentence, you can use promises and their then () callback

 var data = $http({ url: '/Home/GetJson', method: "GET", params: { clientID: cId } }) .then(function (data) { return data.members; }) }; ... ... data.then(function(response){ //play with the data $scope.data=response }) 
+2
source

Source: https://habr.com/ru/post/950634/


All Articles