Call a controller with the data results of 2 functions - angularjs

I am a newbie with Angularjs, and trying to figure it up:
in boardService there are 2 function
var getLiveCards = function () {
return $http.get(endpointService.getLiveCards(), {})
.then(function (response) {
return response.data;
}, function (error) {
return $q.reject(error.data.Message);
}
);
};
var getRelationshipTypes = function () {
return $http.get(endpointService.getRelationshipTypes(), {})
.then(function (response) {
return response.data;
}, function (error) {
return $q.reject(error.data.Message);
}
);
};
and
i am trying to call a controller, with the data received from both of the functions:
vm.relationsEdit = function (card) {
boardService.getLiveCards()
.then(function (data) {
vm.liveCards = data
boardService.getRelationshipTypes()
.then(function (types) {
vm.types = types;
cardRelationsModalService.relationsEdit(card, vm.liveCards, vm.types)
.then(function (response) {
console.log("Card edited: " + response);
});
})
}, onError);
}
When i put a break-point with chrome debugger, in that line: vm.liveCards = data, data contains data from getLiveCards but nothing is happen after that.
What am I doing wrong? how can i get data from the 2 functions and send it to cardRelationsModalService.relationsEdit function?

Related

how to get function return value in a variable using angularjs

Here is my code of angularjs file
$scope.httpPost = function (url, json_form_data) {
$http.post(url, json_form_data)
.then(function (response) {
$scope.responseData = response.data;
return $scope.responseData;
}, function (response) {
$scope.content = "Something went wrong";
});
};
Here is the function in which i am calling the above function
$scope.getAuthToken = function (account_type, auth_type, email, type_of_request) { // type of request means login or signUp
var account_type = account_type;
var form_data = {
'email': email,
"auth_type": auth_type,
"account_type": account_type
};
$scope.responseData = $scope.httpPost($scope.authTokenUrl, form_data);
console.log("value of res");
console.log($scope.responseData);
};
The output of the above code is
value of res
loginAndSignup.js:138 undefined
My question is that How can i access that value which function returning because i needed that value.
I tried the following solution
$scope.httpPost = function (url, json_form_data) {
return $http.post(url, json_form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
};
$scope.login = function (email, auth_token, auth_type, account_type) {
var password = $scope.password;
var form_data = {
//form data
};
var url = $scope.loginUrl;
$scope.httpPost(url, form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
using $q (A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.)
click here for more detail
used this function
$scope.httpPost = function (url, json_form_data) {
var d = $q.defer();
$http.post(url, json_form_data)
.then(function (response) {
d.resolve(response);
}, function (response) {
d.reject(response);
});
return d.promise;
};

Angular Js - Why I am getting Undefiend in controller while I am getting data from service?

I have made a service and I am getting the data but it does not return any thing to controller.
My service. js file
app.factory('countryService', function ($http) {
return {
getCountries: function () {
$http.get('http://abc/countries')
.success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
}
};
});
and here is my controller
$scope.countries = function () {
$scope.countries_data = countryService.getCountries();
console.log($scope.countries_data);
};
What is my mistake ?
You might need to do some structural changes like following
app.factory('countryService', function ($http) {
return {
getCountries: function () {
return $http.get('http://abc/countries'); //just return promise
}
};
});
Let service return the promise, Do other proceedings inside the controller,Define success callback and faiure callback for the same
$scope.countries = function () {
$scope.countries_data = countryService.getCountries().then(success, failure); // callbaks
};
function success(response){
console.log(response); // logs the results
}
function failure(response){
console.log(response); // logs the errors if any
}
Hope this will help
In your service:
app.factory('countryService', function ($http) {
return {
getCountries: function () {
return $http.get('http://abc/countries') // add return this service
.success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
}
};
});
In controller:
$scope.countries = function () {
countryService.getCountries().then(function(res){
$scope.countries_data = res;
console.log($scope.countries_data);
});
};

How can I find out how many records are in the list after AngularJS $resource query()

I'm struggling with something that I think should be pretty simple.
I want to see how many items are returned from a query() but using length isn't working for me.
This my code
getItems = function () {
// retrieve the list
theList = Users.query();
theList.$promise.then(function (res) {
console.log("success");
})
.catch(function (req) {
console.log("error");
})
.finally(function () {
});
return theList;
}
$scope.users = getItems();
console.log($scope.users.length);
This is my $resource:
.factory('Users', function ($resource) {
return $resource('https://example.com/:id', { id: '#id' }, {
update: { method: 'PUT' }
});
})
The console shows 0 even if there are items in the list.
Any idea what I'm doing wrong?
Try
getItems = function () {
// retrieve the list
theList = Users.query();
theList.$promise.then(function (res) {
console.log("success");
$scope.users = res;
console.log($scope.users.length);
})
.catch(function (req) {
console.log("error");
});
}
getItems();
Your getItem() is returning promise. So extract list from it and then try the length just you did inside your getItem();
//try this
getItems().then(function(result) {
$scope.users = result;
console.log('result: %o', $scope.users.length);
})

AngularJS Multiple GET requests, only first returning correctly

I have the following in my controller:
ApiRequest.get('locations').then(function(locations) {
$scope.locations = locations.locations;
});
ApiRequest.get('sublocations').then(function(sublocations) {
$scope.sublocations = sublocations.sublocations;
});
ApiRequest.get('varieties').then(function (varieties) {
$scope.varieties = varieties.varieties;
});
ApiRequest.get('tasks').then(function(tasks) {
$scope.tasks = tasks.tasks;
});
ApiRequest.get('customers').then(function(customers) {
$scope.customers = customers.customers;
});
ApiRequest.get('batches').then(function(batches) {
$scope.batches = batches.batches;
$ionicLoading.hide();
});
The data from each of these requests goes on to poplate select boxes in a form.
Here is my APIRequest service:
return {
get: function(entity) {
if($rootScope.online == false) {
var data = {};
data = JSON.parse(localStorage.getItem('data-' + entity));
console.log(data);
deferred.resolve(data);
} else {
$http.get($rootScope.baseUrl + entity).success(function(data) {
deferred.resolve(data);
})
}
return deferred.promise;
},
}
It would appear that for some reason the results aren't getting back from the service on time to display them in the view.
Is this something to do with the way I am handling the promise?
At first look, you declared the promise with $q outside your function as global (because I don't see inside). Try this one:
get: function(entity) {
var deferred = $q.defer();
if($rootScope.online == false) {
var data = {};
data = JSON.parse(localStorage.getItem('data-' + entity));
console.log(data);
deferred.resolve(data);
} else {
$http.get($rootScope.baseUrl + entity).success(function(data) {
deferred.resolve(data);
})
}
return deferred.promise;
},
your current implementation has little to no error handling and is executing multiple API requests in parallel; I would recommend chaining the promises.
ApiRequest.get('locations').then(function(locations) {
$scope.locations = locations.locations;
return ApiRequest.get('sublocations');
}).then(function(sublocations) {
$scope.sublocations = sublocations.sublocations;
return ApiRequest.get('varieties')
}).then(function (varieties) {
$scope.varieties = varieties.varieties;
return ApiRequest.get('tasks')
}).then(function(tasks) {
$scope.tasks = tasks.tasks;
return ApiRequest.get('customers')
}).then(function(customers) {
$scope.customers = customers.customers;
return ApiRequest.get('batches')
}).then(function(batches) {
$scope.batches = batches.batches;
$ionicLoading.hide();
}, function(_error) {
$ionicLoading.hide();
console.log(_error);
});
and then your service can be simplified; the $http client returns a promise and using $q.when can return a promise also
get: function(entity) {
if($rootScope.online == false) {
var data = {};
data = JSON.parse(localStorage.getItem('data-' + entity));
console.log(data);
$q.when(data);
} else {
return $http.get($rootScope.baseUrl + entity)
}
},

Passing an argument to a service for use with $http.get()

I've created a service which consumes an API. I need to call this service from my controller with an argument that's passed in from a text input on a form.
myAppServices.factory('apiService', function ($http, $q) {
return {
getDocuments: function () {
return $http.get('/api/documents/',
{
params: {
id: '2' // this should not be hardcoded
}
})
.then(function (response) {
if (typeof response.data == 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function (response) {
// something went wrong
return $q.reject(response.data);
});
},
}
My controller looks like this currently...
myApp.controller('homeController', function ($scope, apiService) {
var docs = function () {
apiService.getDocuments()
.then(function (data) {
$scope.docs = data; //console.log(data);
}, function (error) {
// promise rejected ... display generic no data found on table
console.log('error', error);
});
};
}
And my input is simply...
<input type="text" class="form-control" placeholder="Enter ID" ng-model="id">
How can I get the value entered into this input into my service so that I can return the data based on the ID value put into the text input?
You need to pass the parameter to the service method, there is some suggestions that you can consider it.
1-) the promise api and the method on your service.
The right way to use the $q is using the deferred object inself. your service could be like.
myAppServices.factory('apiService', function ($http, $q) {
return {
getDocuments: function (id) {
var deferred = $q.defer();
$http({
method: 'GET',
url: '/api/documents/',
params: {id: id}
}).success(function (response) {
if (typeof response.data == 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
}).error(function (response) {
deferred.reject(response.data);
});
return deferred.promise;
}
}
})
2-) your controller could be like.
myApp.controller('homeController', function ($scope, apiService) {
$scope.getDocs = function () {
apiService.getDocuments($scope.id)
.then(function (data) {
$scope.docs = data; //console.log(data);
}, function (error) {
// promise rejected ... display generic no data found on table
console.log('error', error);
});
};
});
You can just pass additional parameters in your service definition. Then when you use it in your controller, you can pass additional values.
myAppServices.factory('apiService', function ($http, $q) {
return {
getDocuments: function (param1, param2) {
}
Should be something along these lines:
In your controller
apiService.getDocuments($scope.id).then...
In your service
getDocuments: function (idVar) {
return $http.get('/api/documents/',
{
params: {
id: idVar // this should not be hardcoded
}
})

Resources