Combine JSON for two POST in AngularJS - angularjs

I am trying to combine response of one POST data with another input JSON so that it can do another POST function.
Controller 1:-
$scope.master = {};
$scope.addChild = function(net) {
$scope.master = angular.copy(net);
$http.post("url",$scope.master).then( function(data) {
$scope.childData = data;
$scope.dataName = $scope.master.Name;
growl.success("Created a new Child");
console.log(data);
},function (data, status, headers, config) {
growl.error("Something went wrong");
});
console.log($scope.master);
};
Now I want to add the response of this controller ie; $scope.segments = data; to 2nd controller:-
Controller 2:-
$scope.addOverall = {Child: []};
$scope.Create = function() {
$http({
method : 'POST',
url : 'api',
data : $scope.addOverall
}).success(function(data, status, headers, config) {
growl.success("Created a Table");
console.log(data);
},function (data, status, headers, config) {
growl.error("Something is wrong");
});
};
So now , my response data from controller 1 must combine with 2nd controller input over here {Child: []}; inside the [ ] How can I achieve that?

Controller 1:
If you get result in data then use $rootscope for other variable
$rootScope.myGlobalVariable = [] //if response is array or object
$http.post("url",$scope.master).then( function(data) {
$rootScope.myGlobalVariable = data;
Controller 2:
success(function(data, status, headers, config) {
$scope.mylocalVariable = data;
final values in controller 2
for(var i=0; i<$scope.localVariable.length; i++)
{
$rootScope.myGlobalVariable.push($scope.localVariable[i]);
}
console.log('combine json values', $rootScope.myGlobalVariable);
I hope this answer is work for You.
Thanks

Related

How to handle $http response in angularjs using jsreport?

I'm trying to integrate jsreport with angularjs project. I can post jsreport json data but do not know how to handle the reponse to render the jsreport in the browser. Anyone help me
.controller('View1Ctrl', [ '$scope', '$http',function($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
};
var onError = function (data, status, headers, config) {
$scope.error = status;
}
var datajson = {
template:{'shortid':'S1Auk01mb'},
}
var postReq = {
method: 'POST',
url: 'http://localhost:8005/api/report',
data:datajson
};
$http(postReq).success(onSuccess).error(onError);
var getReq = {
method: 'GET',
url: 'http://localhost:8005/api/report'
};
$http(getReq).success(onSuccess).error(onError);
}]);
Change your final get request to look like this:
$http(getReq)
.then(response => {
console.log(response.data);
})
.catch(errorpayload => {
console.log(errorpayload.data);
});
You can then do what you need to with the data object from response. (I logged it out, so you can see what the data will look like.)

Using AngularJs how to write code for Sucess and Failure

How to apply Success And Failed in AngularCtrl
$scope.Btncall = function () {
var xx = MyService.GetDatafromApi();
xx.then(function (d) {
$scope.Employee = d.data;
}
),success(function (success) {
alert('ok');
})
What i understood is that you're asking how to handle a promise return success/fail like the one you get from the $http request service, so here's below an example:
$http.get('http://freegeoip.net/json')
.success(function (data, status, headers, config) {
//TODO When request Success
console.log(data);
$scope.Employee = data;
})
.error(function (data, status, headers, config) {
//TODO When request Failed
console.log(data); //Server Response values if there's any
$scope.Employee = [];
});
This is a sample code which helps you.
$scope.Btncall = function () {
MyService.GetDatafromApi().success(function (data, status,headers)
{
$scope.Employee = data;
})
.error(function (data, status, headers) {
$scope.Employee = [];
});
}
//Call Btncall Function..
$scope.Btncall();

Angularjs service does not perform more than one http request

I have a problem with a service angularjs , do not make more than one http request .
The service :
.factory('checkpoints', function($http, user_auth) {
var promise = $http({
method: "POST",
url: remote_ws + 'index/',
data: user_auth.get,
cache:false
}).
success(function(data, status, headers, config) {
if (data.result == "OK") {
window.localStorage.setItem("last_id", data.update[0].last_id);
window.localStorage.setItem("last_count", data.update[0].last_count);
}
return data;
}).
error(function(data, status, headers, config) {
data.result = "ERROR";
data.status = status;
return data;
});
return promise;
})
In the controller:
var UpdateCheckpoints = function() {
checkpoints.then(function(promise) {
if (promise.data.result == "OK") {
$scope.map.checkpoints = promise.data.markers;
_.each($scope.map.checkpoints, function(marker) {
marker.distance = $scope.c_distance(marker);
marker.onClicked = function() {
onMarkerClicked(marker.id);
};
});
} else {
$location.search({error: true, error_text: session_error}).path("/login");
if (!$scope.$$phase) {
$scope.$apply();
}
}
})
When I call : UpdateCheckpoints ( ), the result is null.
Is done only the first request.
It is a problem with $http or statement of service?
From the documentation:
Angular services are singletons objects or functions ...
The purpose of the service factory function is to generate the single
object, or function, that represents the service to the rest of the
application.
Try changing your factory to something along these lines:
app.factory('checkpointService', function($http, user_auth) {
return {
getCheckpoints: function() {
return $http({
method: "POST",
url: remote_ws + 'index/',
data: user_auth.get,
cache: false
})
.success(function(data, status, headers, config) {
if (data.result == "OK") {
window.localStorage.setItem("last_id", data.update[0].last_id);
window.localStorage.setItem("last_count", data.update[0].last_count);
}
return data;
})
.error(function(data, status, headers, config) {
data.result = "ERROR";
data.status = status;
return data;
});
}
};
});
And call it with:
checkpointService.getCheckpoints().then(function(promise) { ...
Now the checkpointService will be a singleton object, but everytime you call getCheckpoints a new call via the $http service should be made.

How can I make a function call depend on completion of two $http calls in AngularJS?

In my controller I have the following calls:
optionService.init($scope);
optionService.getSubjects1($scope);
optionService.getSubjects2($scope);
optionService.getAbc($scope);
Here's the code for the optionService:
angular.module('common')
.factory('optionService',
['$http',function ($http) {
var factory = {
init: function ($scope) {
$scope.option = {};
},
getSubjects1: function ($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
getSubjects2: function ($scope) {
var url = '/api/Subject2/GetSelect';
$scope.loading++;
$http.get(url)
.success(function (data, status, headers, config) {
$scope.option.subjects2 = data;
$scope.loading--;
})
.error(function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
},
}
return factory;
}]);
Is there a way that I could make the call to optionService.getAbc depend on the completion of both the getSubjects1 and getSubjects2 calls? I will also soon be using Angular 1.2 if this makes any difference.
$q.all(promises) lets you combine multiple promises in to one:
optionService.getAbc = function($scope) {
$q.all([
optionService.getSubjects1($scope),
optionService.getSubjects2($scope)
])
.then(function() {
//...
});
}
Edit. Yes, you need to return promises from your getSubjects functions. To keep code changes to bare minimum, you could do something like this:
optionService.getSubjects1($scope) {
var url = '/api/Subject1/GetSelect';
$scope.loading++;
return $http.get(url)
.then(function (data, status, headers, config) {
$scope.option.subjects1 = data;
$scope.loading--;
}, function (data, status, headers, config) {
$scope.loading--;
alert("Error: No data returned from " + url);
});
}
With $http.then() you create a new promise that can be combined with other promises in getAbc()
You should rewrite your getSubject1 and getSubject2 to return promise. Also passing the $scope to the method and updating the scope from the service method is not a good way of doing things. You service methods should return data which assignable in your code. This makes your services more usable and readable.
If you change getSubject1 and getSubject2 in lines of
getSubjects1: function () {
var url = '/api/Subject1/GetSelect';
return $http.get(url);
}
In your controller you can do
$q.all([
optionService.getSubjects1(),
optionService.getSubjects2()
])
.then(function([data1, data2]) {
//use data1 to update scope for subject1
// use data2 to update scope for subject2
//call any service method.
});

How can I track the start and end of a number of async processes with AngularJS?

I have a loading icon set up on my page that looks like this:
<div class="loading-mask"
data-ng-show="action != null">
<span>{{action}} ...</span>
</div>
When I set $scope.action to a message appears in the loading box.
When loading my page I have a number of different async processes that get data. For example I have:
getUserProfiles: function ($scope) {
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
and:
getSubjects: function ($scope) {
var url = '/api/Subject/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
How can I make it so that the first of these async processes causes a "Loading" message to appear and the last of the async process causes the loading box to not show any more. Note at this time I am not concerned about error messages. I just want the loading to not show when everything is completed.
To expand on what devmiles has said, but to handle the multiple asynchronous functions, you will want to set a loading flag on your first function to be called. I.e.:
getUserProfiles: function ($scope) {
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
});
},
And then you will want to wrap each of your asynchronous functions in a promise, like so:
getUserProfiles: function ($scope) {
var deferred = $q.defer();
$scope.loading = true;
var url = '/api/UserProfile/GetSelect';
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.userProfiles = data;
deferred.resolve();
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
deferred.reject();
});
return deferred;
},
You can then call $q.all on all of your asynchronous functions, and the success callback of this will occur once all asynchronous functions have resolved:
$q.all([getUserProfiles, getSubjects]).then(function() {
$scope.loading = false;
}
This means once all of your functions have resolved, loading will be set to false.
NB: If you want to access the data of your callbacks, you can pass it in as a parameter of "deferred.resolve(x)", and then in your $q.all callback, it will be available as function(x) { do something with x }.
Hope this helps!
EDIT: Don't forget to pass in angular's promise service, $q, to the controller where your functions are.
Just set some boolean flag on when your controller is being instantiated and reset this flag in your success/error functions.
.controller('MyCtrl', function ( $scope ) {
$scope.isLoading = true;
$http({ method: 'GET', url: url })
.success(function (data, status, headers, config) {
$scope.option.subjects = data;
$scope.isLoading = false;
})
.error(function (data, status, headers, config) {
alert("Error: No data returned from " + url);
$scope.isLoading = false;
});
});
Use ng-show with this flag to show your loading thingy.

Resources