How to handle a resolved $promise with no data - javascript

In my application, I have a form in which the user can add multiple records. When the page is loaded, I need to make a GET request to check the DB for existing records. If there are records that exist, I populate them on the page. No problem there.
The issue I'm having is when the DB has no existing records, the server return a 204 No Content. In the controller, the success function still gets executed but there is no data only the $promise object and $resolved: true.
Here is the code:
Factory:
return $resource (
https://my.backend/api/records/:id",
{},
{
"getExistingRecords": {
method: 'GET',
isArray: false,
params: {id: '#id'},
withCredentials: true}
}
)
Controller:
function initialize(id){
alertFactory.getExistingRecords({id: id})
.$promise
.then(function (records){
if(records){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}
},function(error){
Notification.error(error);
});
}
initialize(id);
When the server returns "204 No Content" I get this from the console
Console Image
Is the only way to handle this to check for object properties of the records object?
For example:
function initialize(id){
alertFactory.getExistingRecords({id: id})
.$promise
.then(function (records){
if(records.recordName){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}
},function(error){
Notification.error(error);
});
}
initialize(id);
Or am I missing something else?

It would have been better if you could get status code with response. There is not direct way for that. But you can workaround with an interceptor:
var resource = $resource(url, {}, {
get: {
method: 'GET'
interceptor: {
response: function(response) {
var result = response.resource;
result.$status = response.status;
return result;
}
}
}
});
And now you can:
if(records.$status === 200){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}

I think you should return an empty list if there if no registers.

Related

is it possible not to execute the promise (.then ()) in the controller when there is an error in a web request?

I'm currently using a factory called http that when I invoke it, I make a web request. this receives as a parameter the url of the web request.
app.factory('http', function ($http) {
var oHttp = {}
oHttp.getData= function (url) {
var config={
method: 'GET',
url: url
}
return $http(config).then(function(data) {
oHttp.data=data.data;
},function(response) {
alert("problem, can you trying later please?")
});
}
return oHttp;
});
function HelloCtrl($scope, http) {
http.getData('https://www.reddit.com/.json1').then(function(){
if(http.data!=undefined){
console.log(http.data)
}
})
}
I would like the promise not to be executed on the controller if the result of the web request is not satisfied or there is a problem. is there any better solution? I want to avoid doing this every time I make a web request, or do not know if it is the best way (see the if):
//I am putting "1" to the end of the url to generate an error.
http.getData('https://www.reddit.com/.json1').then(function(){
//validate that the result of the request != undefined
if(http.data!=undefined){
alert(http.data.kind)
}
})
In my real project I make n web requests using my factory http, I do not want to do this validation always. I do not know if I always have to do it or there is another solution.
this is my code:
https://plnkr.co/edit/8ZqsgcUIzLAaI9Vd2awR?p=preview
In rejection handlers it is important to re-throw the error response. Otherwise the rejected promise is converted to a successful promise:
app.factory('http', function ($http) {
var oHttp= {};
oHttp.getData= function (url) {
var config={
method: 'GET',
url: url
}
return $http(config).then(function(response) {
̶o̶H̶t̶t̶p̶.̶d̶a̶t̶a̶=̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶;̶
return response.data;
},function(response) {
alert("problem, can you trying later please?")
//IMPORTANT re-throw error
throw response;
});
}
return oHttp;
});
In the controller:
http.getData('https://www.reddit.com/.json1')
.then(function(data){
console(data)
}).catch(response) {
console.log("ERROR: ", response.status);
});
For more information, see You're Missing the Point of Promises.
In Service
app.factory('http', function ($http) {
var oHttp = {}
oHttp.getData= function () {
return $http({
method: 'GET',
url: 'https://www.reddit.com/.json1'
});
}
return oHttp;
});
In controller
function HelloCtrl($scope, http) {
var httpPromise = http.getData();
httpPromise.then(function(response){
console.log(response);
});
httpPromise.error(function(){
})
}
So I tried this in codepen having ripped your code out of plinkr
https://codepen.io/PocketNinjaDesign/pen/oGOeYe
The code wouldn't work at all...But I changed the function HelloCtrl to a controller and it seemed happier....?
I also set response.data to default to an empty object as well. So that way if you're populating the data in the page it will be empty if nothing arrived. You can then in some instances on the site check the length if it's really required.
app.factory('http', function ($http) {
var oHttp = {}
oHttp.data = {};
oHttp.getData= function (url) {
var config = {
method: 'GET',
url: url
}
return $http(config).then(function(response) {
oHttp.data = response.data || {};
}, function(response) {
alert("problem, can you trying later please?")
});
}
return oHttp;
});
app.controller('HelloCtrl', function($scope, http) {
http.getData('https://www.reddit.com/.json').then(function(){
alert(http.data.kind);
})
});

AngularJS Http Post - 500 Internal Server Error

I know there's a lot of other 500 (Internal Server Error) questions out there, but reading them is still not helping my case.
I am working on two angularjs methods that have $http post calls in them.
FIRST PROBLEM
The first successfully hits the server-side controller, and returns a JSON object as I expect it, but my drop downs are not being filled by the result of the factory call.
One thing that concerns me, is the console output. (As you'll see in the code below I have several print statements.) The URL is printed, and then my drop down options field is printed as undefined, and then the response from the server comes back with the response. Do I need to tell the JS to wait for the response? Some sort of ASYNC?
SECOND PROBLEM
I have the exact same http post method call (but with new variables), and I get the 500 (Internal Server Error) error message. The server-side ctrl method is not being hit for this call (based on break point in ctrl).
Questions
How do I fill my drop down successfully with the result of the
$http.post call?
Why is my second $http.post method creating the 500 (Internal Server Error)?
Javascript
'use strict';
var app = angular.module('LineModule', ['ngMaterial']);
app.controller("LineCtrl", ['$scope', '$http', 'LineService',
function ($scope, $http, LineService) {
$scope.Types = LineService.get_DropDownList("Type");
console.log("Types:"); console.log($scope.Types);
$scope.Statuses = LineService.get_DropDownList("Status");
$scope.FundingSources = LineService.get_DropDownList("Funding_Source");
...
$scope.get_DeptLeader = function () {
$scope.SelectedLeader = LineService.get_DeptLeader($scope.CPOC_Title, $scope.CostCenter_ID);
};
}]);
app.factory('LineService', ["$http", function ($http) {
return {
...
***FIRST METHOD***
get_DropDownList: function (field) {
var info = {
section: 'Line',
field: field
};
var URL = getBaseURL() + 'DBO/DropDown_GetList';
console.log(URL);
var DropDown;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DropDown = response.data;
console.log(DropDown);
return DropDown;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
***SECOND METHOD***
get_DeptLeader: function (CPOC_Title, CostCenter_ID) {
console.log("call get leader");
if (CPOC_Title < 1 || CPOC_Title == undefined) { return "No Title Selected"; }
if (CostCenter_ID < 1 || CostCenter_ID == undefined) { return "No Cost Center Selected"; }
console.log(CPOC_Title);
console.log(CostCenter_ID);
var info = {
Leader_ID: CPOC_Title,
CostCenter_ID: CostCenter_ID
};
var URL = getBaseURL() + 'DBO/DeptLeader_GetCurrent';
console.log(URL);
var DeptLeaders;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DeptLeaders = response.data;
console.log(DeptLeaders);
return DeptLeaders;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
};
}]);
DBO Controller: Server-Side
[HttpPost]
public JsonResult DeptLeader_GetCurrent(string Leader_ID, string CostCenter_ID)
{
try {
List<SelectListItem> DL = DB.DeptLeader_GetByIDs(Leader_ID, CostCenter_ID);
return Json(DL, JsonRequestBehavior.AllowGet);
}
catch (Exception e){
string error = e.ToString();
return null;
}
}
[HttpPost]
public JsonResult DropDown_GetList(Sections section, DropDownFields field)
{
return Json(DB.GetDropDownValues(section, field), JsonRequestBehavior.AllowGet);
}
CSHTML
<div ng-app="LineModule" ng-controller="LineCtrl" class="container col-md-12">
...
<select ng-model="Type_ID" class="form-control" required>
<option ng-value="T.Value" ng-repeat="T in Types">{{T.Text}}</option>
</select>
...
<select ng-model="CPOC_Title" class="form-control" ng-change="get_DeptLeader()">
<option ng-value="D.Value" ng-repeat="D in DeptLeaders">{{D.Text}}</option>
</select>
{{SelectedLeader}}
...
</div>

Return Object in $rootScope Function (AngularJS)

I am trying to return an object from a $rootScope function called retrieveUser() in AngularJS. The object is returned. I have run console.log() on the response of the function ran when $http is successful. Here is my $rootScope function:
$rootScope.retrieveUser = function() {
var apiUrl = "http://104.251.218.29:8080";
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
$http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
} else {
return response.data;
}
})
} else {
window.location = "/auth/login";
}
};
With this method, I access it in my controller such as this (and console.log() just to test my work):
vm.user = $rootScope.retrieveUser();
console.log($rootScope.retrieveUser());
But, I have yet to get this to work. I have tried specifying specific objects in an array in my $rootScope function. I know it runs, because I have the $rootScope consoling something when it is run, and it shows a console.log() of the response of the $http request. It looks like this:
Object {event: "success", table: Object}
event:"success"
table:Object
__proto__:Object
Yet, when I console.log() the vm.user with the function $rootScope.retrieveUser(), even though the function is supposed to be returning the object, I simply receive "undefined".
I have been banging my head on this for days, read some articles on functions/objects and I still cannot figure this out. We're two days in.
try this:
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
//return a promise
return $http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
}
else {
return response.data;
}
})
}
else {
window.location = "/auth/login";
}
and
$rootScope.retrieveUser().then(function(user){vm.user = user;})
What you are returning from retrieveUser when your cookie is set is what $http returns, which is a promise. Try this:
$rootScope.retrieveUser().then(function(user){vm.user = user;})
retrieveUser fn doesn't return your data :)
$http is asynchronous function and you should read about promises
function handleUser(user){
//do something
}
function retrieveUser(callback){
$http({...}).then(function(response){
callback(response.data.user);
});
}
//how to use it:
retrieveUser(handleUser);
but first of all you may need a service for getting some data instead of using $rootScope
and secondly you can pass a user in your template in script tag
then you don't need another http request and user will be globaly available
<script>var user=<?php echo json_encode($user);?></script>

Angular services: is it bad practice to assign response to an object or should I only use resolve

I have seen this code, which works for me but I wonder if it's bad practice to create an object inside the service- assign it to this and then to assign the response to the object in the success callback of the http get method.
.service("personDataService", function($http, $q) {
var person = this;
person.record = {};
var endPoint = 'https://api.something.com';
person.getInformation = function() {
var defer = $q.defer();
$http.get(endPoint)
.success(function(response) {
/*
here i'm assigning response to person.record and also using resolve.
but is this bad practice to assign response directly to person?
*/
person.record = response;
defer.resolve(response);
})
.error(function(err, status) {
defer.reject(err);
})
return defer.promise;
}
return person;
}
Then in my controllers code I am calling the personDataService.record directly to check if it's empty.
i.e.
Object.keys(personDataService.record).length
Is this bad practice to be using personDataService.album directly?
It would be better if instead of assigning a response to an object to use then method from inside your controller and have the response delivered there. Another thing that you shoud do is to remove the $http legacy promise methods success and error that have been deprecated and use the standard then method. This is an example of how to use then method.
angular.module('starter')
.factory('services', services);
function services($http) {
var services = {
someService: someService,
};
return services;
//someService service
function someService() {
var req = {
method: 'GET',
url: 'https://api.something.com',
headers: {
'Accept' : 'application/json',
'contentType': "application/json"
}
};
return $http(req);
};
}
Then from your controller call the service like this:
services.someService().then(
function(response) {
//do whatever is needed with the response
console.log(response);
},
function (error) {
console.log(error);
}
);

AngularJS: transform response in $resource using a custom service

I am trying to decorate the returned data from a angular $resource with data from a custom service.
My code is:
angular.module('yoApp')
.service('ServerStatus', ['$resource', 'ServerConfig', function($resource, ServerConfig) {
var mixinConfig = function(data, ServerConfig) {
for ( var i = 0; i < data.servers.length; i++) {
var cfg = ServerConfig.get({server: data.servers[i].name});
if (cfg) {
data.servers[i].cfg = cfg;
}
}
return data;
};
return $resource('/service/server/:server', {server: '#server'}, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(data, header) {
return mixinConfig(angular.fromJson(data), ServerConfig);
}
},
get: {
method: 'GET',
isArray: false,
transformResponse: function(data, header) {
var cfg = ServerConfig.get({server: 'localhost'});
return mixinConfig(angular.fromJson(data), ServerConfig);
}
}
});
}]);
It seems I am doing something wrong concerning dependency injection. The data returned from the ServerConfig.get() is marked as unresolved.
I got this working in a controller where I do the transformation with
ServerStatus.get(function(data) {$scope.mixinConfig(data);});
But I would rather do the decoration in the service. How can I make this work?
It is not possible to use the transformResponse to decorate the data with data from an asynchronous service.
I posted the solution to http://jsfiddle.net/maddin/7zgz6/.
Here is the pseudo-code explaining the solution:
angular.module('myApp').service('MyService', function($q, $resource) {
var getResult = function() {
var fullResult = $q.defer();
$resource('url').get().$promise.then(function(data) {
var partialPromises = [];
for (var i = 0; i < data.elements.length; i++) {
var ires = $q.defer();
partialPromisses.push(ires);
$resource('url2').get().$promise.then(function(data2) {
//do whatever you want with data
ires.resolve(data2);
});
$q.all(partialPromisses).then(function() {
fullResult.resolve(data);
});
return fullResult.promise; // or just fullResult
}
});
};
return {
getResult: getResult
};
});
Well, Its actually possible to decorate the data for a resource asynchronously but not with the transformResponse method. An interceptor should be used.
Here's a quick sample.
angular.module('app').factory('myResource', function ($resource, $http) {
return $resource('api/myresource', {}, {
get: {
method: 'GET',
interceptor: {
response: function (response) {
var originalData = response.data;
return $http({
method: 'GET',
url: 'api/otherresource'
})
.then(function (response) {
//modify the data of myResource with the data from the second request
originalData.otherResource = response.data;
return originalData;
});
}
}
});
You can use any service/resource instead of $http.
Update:
Due to the way angular's $resource interceptor is implemented the code above will only decorate the data returned by the $promise and in a way breaks some of the $resource concepts, this in particular.
var myObject = myResource.get(myId);
Only this will work.
var myObject;
myResource.get(myId).$promise.then(function (res) {
myObject = res;
});

Categories

Resources