How to pass array as parameter to $http.get in Angularjs - javascript

Problem Statement
I have a javascript array which i want to pass as a parmeter to $http.get in AngularJs. This array will be passed to action method in MVC. what should be the syntax? Please Help me. I am stuck here.
The array being passed is javascript array
Angular Directive
$scope.selectedIdArray = [];
$scope.selectedIdArray.push({ id: $scope.selectedId })
$scope.$parent.getProjects($scope.selectedIdArray);
Angular Controller
$scope.getProjects = function (selectedIdArray) {
$http.get('Home/GetAllProjects', { params: { "parentId[]": selectedIdArray } })
.then(function (data) {
$scope.projects = [];
angular.forEach(data.data, function (value, index) {
$scope.projects.push({ id: value.N_LevelID, label: value.T_LevelName }
);
});
})
.catch(function (data) {
console.error('Gists error', data.status, data.data);
})
}
MVC Controller Action Method
public JsonResult GetAllProjects(int?[] parentId = null)
{
iMetricsEntities dbcontext = new iMetricsEntities();
JsonResult jr = new JsonResult();
if (parentId == null)
{
jr.Data = dbcontext.Levels.Where(objelevel => objelevel.N_LevelTypeID == 2 && objelevel.B_Active);
jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
//return new JsonResult
//{
// Data = dbcontext.Levels.Where(objelevel => objelevel.N_LevelTypeID == 2 && objelevel.B_Active),
// JsonRequestBehavior = JsonRequestBehavior.AllowGet
//};
}
else if (parentId != null)
{
foreach (var id in parentId)
{
jr.Data = dbcontext.Levels.Where(objelevel => objelevel.N_LevelTypeID == 2 && objelevel.B_Active && objelevel.N_ParentID == id);
jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
}
return jr;
}

If you define your controller action like this:
public JsonResult GetAllProjects(int[] parentId)
{
// Stuff goes here
}
You can call it like this:
$http.get('Home/GetAllProjects', { params: { "parentId": [1, 2, 3, 42] } })
.then(function(response) {
// stuff goes here
});
The reason this works is because query strings can be specified multiple times. Both $http and MVC interpret these as arrays.
In the above example, this is the URL that gets generated by $http, which the controller action model binds to an array:
http://localhost:56976/Home/GetAllProjects?parentId=1&parentId=2&parentId=3&parentId=42

$http(
method: 'GET',
url: ''Home/GetAllProjects'',
params: {
parentId: JSON.stringify(selectedIdArray )
}
)

Related

How to record a user has been registered to an event - SQLite

I am trying to update an event within my calendar using https://fullcalendar.io/ to show if the current user is registered or not for that event to show that the event color will turn from green to red.
The below methods are within my service method.
public List<TimeTableEvent> GetAllEvents()
{
return db.TimeTableEvents.ToList();
}
public List<EventAttendance> GetAllMembershipEvents(int membershipId)
{
var events = GetAllEvents();
var attendances = db.Attendances.Where(m => m.MembershipId == membershipId);
var membershipEvents = events.Select(e => new EventAttendance
{
Event = e,
Attendance = attendances.FirstOrDefault(a => a.TimeTableEventId == e.Id)
}).ToList();
return membershipEvents;
}
public Attendance AddMembershipToEvent(int membershipId, int eventId)
{
var attendance = new Attendance { MembershipId = membershipId, TimeTableEventId = eventId,
AttendanceStatus = AttendanceStatus.Pending };
db.Attendances.Add(attendance);
db.SaveChanges();
return attendance;
}
I am then using this method within the controller
public JsonResult GetMembershipEvents(int membershipId)
{
var events = service.GetAllMembershipEvents(membershipId);
return Json(events);
}
And then I have a javascript method within my View. That is shown below.
function FetchEventsAndRenderCalendar() {
var userId = 1;//User.Claims.FirstOrDefault(c => c.Type == "Id");
events = []; // clear existing events
$.ajax({
type: "GET",
url: "/Timetable/GetMembershipEvents/" + userId,
success: function (data) {
$.each(data, function (i, json) {
events.push(
{
id: json.event.id,
title: json.event.title,
description: json.event.description,
start: moment(json.event.start),
end: moment(json.event.end),
color: json.isRegistered?"Red":"Green",
allDay: json.event.allDay
}
);
})
I am adding a user to an event so one of the events should be red when it complies. However, it is still showing as green.
Any help would be greatly appreciated.
You can try changing your function from this:
function FetchEventsAndRenderCalendar() {
var userId = 1;//User.Claims.FirstOrDefault(c => c.Type == "Id");
events = []; // clear existing events
$.ajax({
type: "GET",
url: "/Timetable/GetMembershipEvents/" + userId,
success: function (data) {
$.each(data, function (i, json) {
events.push(
{
id: json.event.id,
title: json.event.title,
description: json.event.description,
start: moment(json.event.start),
end: moment(json.event.end),
color: json.isRegistered?"Red":"Green",
allDay: json.event.allDay
}
);
})
to
// Function in which you use await should haveasync delaration
async function FetchEventsAndRenderCalendar() {
var userId = 1;//User.Claims.FirstOrDefault(c => c.Type == "Id");
events = []; // clear existing events
// await means wait for the call to finish and then proceed
const response = await fetch('http://www.example.com/Timetable/GetMembershipEvents/' + userId, {
method: 'GET',
headers: {"Content-Type": "application/json"}// Set required headers. Check Postman call you made.
});
console.log(response);
//Continue doing stuff with response
}
Lot of nodejs projects do this. Try this. If this does not work, try adding async: false in your ajax call.

Value returned by service not update in controller's variable in angularjs

function getList() {
SubCategoryService.getAllList().then(function (response) {
$scope.subCategoryList = response.data;
$scope.subCategoryDetailsList = [];
var subCategoryDetails = [];
for(var i=0; i < $scope.subCategoryList.length; i++) {
var subCategoryListData = $scope.subCategoryList[i];
var subcategory = {
'id' : subCategoryListData.id,
'category' : '',
'name' : subCategoryListData.name,
'created_on' : subCategoryListData.created_on,
'modified_on' : subCategoryListData.modified_on,
'is_deleted' : subCategoryListData.is_deleted,
'is_active' : subCategoryListData.is_active,
'image_name' : subCategoryListData.image_name,
'image_path' : subCategoryListData.image_path
}
CategoryService.getCategoryById(subCategoryListData.category_id).then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
}, function(error) {
swal("Error", error.data, "error");
})
subCategoryDetails.push(subcategory);
}
console.log(JSON.stringify(subCategoryDetails));
}, function (error) {
swal("Error", "Something went wrong", "error");
});
}
CategoryService:
this.getCategoryById = function(id) {
return $http({
url: globalUrl.baseurl + 'category/getCategoryById/' + id,
method: 'GET'
})
}
in the above code i am tring to fetch data from CategoryService service and it successfully return the data within the CategoryService.getCategoryById function. Now i am trying to assign returned value by service to subcategory.category which is present in controller. but my problem is it is not updateing the value in subcategory.category.
my guess is:
you are pushing the new variabile inside the array BEFORE the API call is executed (because of the js callback), can you try something like:
CategoryService.getCategoryById(subCategoryListData.category_id)
.then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
// PUSHING AFTER API RETURNS THE VALUE
subCategoryDetails.push(subcategory);
}, function(error) {
swal("Error", error.data, "error");
})
// subCategoryDetails.push(subcategory);

Angular can't retrive simple Integer as a backend reposne

From the backend I'm getting simple integer:
#PreAuthorize("hasAnyAuthority('WORKER')")
#RequestMapping(value = "/countFiles", method = RequestMethod.GET)
public ResponseEntity<Integer> countFiles(HttpServletRequest request){
return fileService.countFiles(request);
}
UPDATE - Service site:
public ResponseEntity<Integer> countFiles(HttpServletRequest request) {
Principal name = request.getUserPrincipal();
if (name.getName() == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
User userByLogin = userRepository.findUserByLogin(name.getName());
fileDao.countByUser(userByLogin);
return new ResponseEntity<Integer>(fileDao.countByUser(userByLogin), HttpStatus.OK);
}
At frontend site created simple method:
angular.module('sbAdminApp').factory('FileService', function ($resource) {
var service = $resource('api/file', {
id: '#id'
}, {
saveFile: {
method: 'POST',
url: 'api/file',
headers: {'content-Type': undefined}
},
countFiles: {
method: 'GET',
url: 'api/file/countFiles',
responseType: 'text'
}
});
return service;
});
Angular controller:
var app = angular.module('sbAdminApp');
app.controller('GoogleMapCtrl', function ($scope, $log, uiUploader, FileService, $http) {
$scope.name = "Hello";
console.log('count', FileService.countFiles());
});
But the output looks like:
So there is no my clount at all..It should be 27.
================UPDATE=====================
var val;
FileService.countFiles().$promise.then(function(response) {
console.log('respone', response.data);
val = response.value();
});
console.log('val', val)
Abouve code return both for var and when I print undefinded
Your Service/Factory method 'countFiles' returns a promise. So you have to "wait" for the promise to be resolved.
FileService.countFiles().$promise.then(function(response) {
$scope.val = response.value();
}
The console.log('val', val) would get executed first if written outside since we wait for the promise to get resolved. So, it should be,
var val;
FileService.countFiles().$promise.then(function(response) {
console.log('respone', response.data);
//val = response.value;
//console.log('val', val);
});

Parse xml tag in a AngularJS feed

I need parse the enclosure tag in order to get the url image. It's assumed I should get the MIXED OUTPUT with the json+xml code but I get a undefined value from the enclousure tag when I try parse it. I'm doing this like I saw at this post > Google Feed Loader API ignoring XML attributes < .In addition I tried to get the MIXED format writing the url manually but It doesn't work. There is my whole code. How could I know that Im getting the mixed json output?
var feeds = [];
var entryImageUrl = [];
angular.module('starter.controllers', ['ngResource','ngLocale'])
.factory('FeedLoader', function ($resource) {
return $resource('http://ajax.googleapis.com/ajax/services/feed/load', {}, {
fetch: { method: 'JSONP', params: {v: '1.0', callback: 'JSON_CALLBACK', output: 'json_xml'} }
});
})
.service('FeedList', function ($rootScope, FeedLoader) {
this.get = function() {
var feedSources = [
{title: 'Heraldo De Barbate', url: 'http://www.heraldodebarbate.es/rss/last'},
];
if (feeds.length === 0) {
for (var i=0; i<feedSources.length; i++) {
FeedLoader.fetch({q: feedSources[i].url, num: 10}, {}, function (data) {
var feed = data.responseData.feed;
**var entryImageUrl = feed.xmlNode.getElementsByTagName("enclosure")[i].getAttribute("url");**
feeds.push(feed);
});
}
}
return feeds;
};
})
.controller('FeedCtrl', function ($scope, FeedList,$timeout) {
$scope.update = function(){
$scope.feeds = FeedList.get();
$scope.$on('FeedList', function (event, data) {
$scope.feeds = data;
// $scope.entryImageUrl
console.log(feeds);
});
$timeout(function() {
$scope.$broadcast('scroll.refreshComplete');
}, 500);
}
})
How could I know that Im getting the mixed json output?
Use a test for tags within JSON:
function testMe(node)
{
return /</.test(JSON.stringify(node) )
}
then run it on the feed:
var mixed_format = testMe(feed);
and call another function which parses the data:
if (mixed_format)
{
mixed_parser(feed)
}
else
{
json_parser(feed)
}

Knockout and breeze.js take method is not working Paging

Datacontext.js
var manager = new breeze.EntityManager('breeze/BreezeData');
function getMenuItems() {
var query = new breeze.EntityQuery("Products").take(5);
return manager.executeQuery(query);
}
Products.js
function loadProducts() {
return datacontext.getMenuItems().then(function (data) {
data.results.forEach(function (item) {
self.menuProducts.push(item);
});
}).fail(function (data) {
logger.logError('Failed to load Products', null, "", true);
});
}
Action Method
[HttpGet]
public IEnumerable<MenuItem> Products()
{
var venueId = GetCurrentVenue().ID;
return _contextProvider.Context.MenuItem.Where(mi => mi.Venue.ID == venueId);
}
It returns almost 45 records but i am using take(5) here and that take isn't working and returning the same result.I am a newbie so i have just started to implement it.
Thanks in advance..
Change action method to:
[HttpGet]
public IQueryable<MenuItem> Products()
{
var venueId = GetCurrentVenue().ID;
return _contextProvider.Context.MenuItem.Where(mi => mi.Venue.ID == venueId);
}
In case it still doesn't work, try adding orderBy in case server isn't sure what would actually be first 5 items.

Categories