OData in AngularJS returns empty Array - angularjs

coming from this working example: http://jsfiddle.net/h22f7596/ , I am trying to display the content of a json-file from my own OData Service in AngularJS.
HTML:
<div ng-repeat="Adressen in results">
{{Adressen.Street}}
<strong style="float:right">
{{Adressen.PLZ}}
</strong>
</div>
</div>
JS:
var myModule = angular.module("MyModule",['ODataResources']);
myModule.controller("MyController",function($scope,$odataresource){
$scope.results =
$odataresource("https://xsgeos0015309874trial.hanatrial.ondemand.com/s0015309874trial/xsgeo/geotabelle/geoDB/GeotabelleODataService.xsodata/Adressen", [],
{
odata:{
method: 'GET',
isArray: true,
transformResponse: function (data) {
return angular.fromJson(data).value;
}
}
})
.odata()
.format("json")
.filter("Street", "Kölner Straße")
.filter("Hausnummer", "22")
.take(5)
.query();
});
I dont know why no data is displayed, because in Chromes console, I can see that the OData request is transferred succesfully, but it is not displayed in my controller and when I look at console.log($scope.results) it shows me an empty array.
Please take a look at my example and tell me what I did wrong: http://jsfiddle.net/h22f7596/123/
Thank you in advance.
/edit: Updated Fiddle.

You were accessing the data wrong. If you would have printed the entire object you would have seen:
Object: {
d: {
results: {
....
}
}
}
Change your return to:
return angular.fromJson(data).d.results
Fiddle: http://jsfiddle.net/h22f7596/124/

Related

ng-repeat not displaying data when fetch via factory service

Need help to understand my mistake/ to display data on page.
I gone through almost every question on forum saying "ng-repeat not working". But still not able to find out the answer.
(Please note: First time I tried to fetch data by creating factory service with $http)
Please take a look at my below JavaScript code (Module, Controller and factory defined at one place)
//App declaration
var myApp = angular.module("appLeadsLogRpt", []);
//Controller declaration
myApp.controller('controllerLeadsLogRpt', ['dataService', fncontrollerLeadsLogRpt]);
function fncontrollerLeadsLogRpt(dataService) {
var vm = this;
//Table headers
vm.TableHeaders = ["Lead Id", "Source", "Create Date", "Status", "Contact Id", "Customer Name", "AssignedTo", "Mail Content", "Closed Reason", "Last Lead Note"];
dataService.getAllData()
.then(getData,null)
.catch(showError);
function getData(data) {
vm.LeadsLogRptData = JSON.parse(data);
//console.log(JSON.parse(data));
}
function showError(errMsg) {
console.log(errMsg);
}
}
//Factory Service to fetch data
myApp.factory('dataService', ['$http', DataService]);
function DataService($http) {
return {
getAllData: GetAllData
};
function GetAllData() {
return $http({
method: 'get',
url: 'DataHandler.ashx?method=leadsReport&listId=504473'
})
.then(sendResponseData)
.catch(sendError)
}
function sendResponseData(response) {
return response.data;
}
function sendError(response) {
return response.status;
}
}
</script>
And my Html like below:
<div id="DvContent" style="width:100%" data-ng-app="appLeadsLogRpt">
<div style="width:100%;" data-ng-controller="controllerLeadsLogRpt as vm1">
<input type="text" id="txtJsonData" value='<%=jsonLeadsLogRpt %>' style="display:none" />
<div><h3>Leads Log Report</h3></div>
<div style="text-align:right;margin-bottom:2px;padding-right:2px;">
<img src="/mp_images/excelicon.gif" border=0 width=22 height=22 alt="Open in Excel">
</div>
<div id="divExportToExcel">
<table style="width:100%" id="tblLeadLogRpt" class="table table-bordered">
<thead>
<tr style="background-color:#CCCCCC">
<th data-ng-repeat="item in vm1.TableHeaders" class="ng-cloack">{{item}}</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item1 in vm1.LeadsLogRptData">
<td class="ng-cloack">{{item1.A_LeadId}}</td>
<td class="ng-cloack">{{item1.B_Source}}</td>
<td colspan="8"></td>
</tr>
<tr data-ng-if="LeadsLogRptData.length==0"><td colspan="10">Data Not Found</td></tr>
</tbody>
</table>
</div>
</div>
</div>
If I assign hard coded data return by server to ng-repeat it works fine
Please let me know what I am doing wrong.
One more question.
In factory I fetch data by calling get method of $http
If I want to call it by Post method, how do I pass params?
In Jquery, I doing it following way.
$.ajax({
url: 'AbcdHandler.ashx',
type: 'POST',
data: {
'method': 'ABCData',
'StartDate': startDate,
'EndDate': endDate
},
success: function (result) {
return JSON.parse(result);
},
error: OnError
});
Thanks in advance for reading and helping.
My latest observation:
when I write data on console, got this. (take a look on function getData(data))
[{"A_LeadId":"426429","B_Source":"LabX"},{"A_LeadId":"429369","B_Source":"LabX"},{"A_LeadId":"430586","B_Source":"Info"},{"A_LeadId":"430589","B_Source":"Info"},{"A_LeadId":"433848","B_Source":"LabX"},{"A_LeadId":"448592","B_Source":"Info"},{"A_LeadId":"451795","B_Source":"Bid"},{"A_LeadId":"453008","B_Source":"Low Bid"},{"A_LeadId":"453009","B_Source":"Low Bid"},{"A_LeadId":"453010","B_Source":"Low Bid"},{"A_LeadId":"455736","B_Source":"Info"},{"A_LeadId":"455743","B_Source":"Info"},{"A_LeadId":"457030","B_Source":"Info"},{"A_LeadId":"457052","B_Source":"LabX"},{"A_LeadId":"461503","B_Source":"Manually Entered"}]
If I copy this and directly assign to vm.LeadsLogRptData, system shows me output on screen properly.
e.g. vm.LeadsLogRptData = [{"A_LeadId":"426429","B_Source":"LabX"},......];
One more thing. When I check length of data, it shows me 621. ({{vm.LeadsLogRptData.length}})
Actually there are only 15 curly brackets pair ({}) and system should show me length as 15
Hope I explain/describe my issue correctly.
(Need something which converts my data properly in Json format)
Thanks,
I got answer
Just use eval with Json.parse and system start displaying data properly
e.g. vm.LeadsLogRptData = eval(JSON.parse(data));
Anyone please explain me the logic behind this?
Thanks to every one who read and replied so far.
Maybe you should use params property of $http object, like:
function GetAllData() {
return $http({
method: 'GET',
url: 'http://localhost:12345/DataHandler.ashx',
params: {method: "leadsReport", listId: 504473}
})
.then(sendResponseData)
.catch(sendError)
}
If you want to perform POST request, you should use it like this:
function PostData() {
return $http({
method: 'POST',
url: 'http://localhost:12345/DataHandler.ashx',
data: {exampleData: exampleData}
})
.then(sendResponseData)
.catch(sendError)
}
Remember to change http://localhost:12345/ for your server URL.

why does my angularjs $http.get request with params not return filtered results?

I apologise if this is a stupid question. I am running a $http.get() request in my client controller to retrieve objects including a particular id. If anyone can point me in the right direction I would be very grateful. Thanks in advance!
$http
.get('api/offers', {
params: {
taskId: vm.task._id
}
})
.success(function (data,status) {
vm.task.offers = data;
console.log(data);
// if (vm.task.offers.taskId === vm.task._id) {
// console.log(vm.task.offers);
// }
});
However, the request is returning all data in the mongodb document.
I have tried filtering in my html page but also not working.
<ul class="list-group" ng-repeat="offer in vm.task.offers | filter: { offer.taskId : vm.task._id } : true">
Get request is getting /api/offers?taskId=570999f043131bb7ade86185 in my browser network resources, again this end point returns all entries in my document, rater than filtered by the taskId.
On ng-repeat filtering you made a mistake, have it like below.
ng-repeat="offer in vm.task.offers | filter: { taskId : vm.task._id } : true"

Howto submit a form with Angular and displaying results on a different page

I'm trying to submit a form from a HTML page using angular.
My HTML code is:
<form role="search">
<input type="text" ng-model="searchSring">
<button type="submit" ng-click="searchPerson(searchString);">Get it!
</button>
</form>
The searchPerson function is calling some PHP page using Ajax and data is successfully retrieved from it.
What I want is when the user has clicked the Get it! button, he should be routed to another HTML page where I would like to display the results. I've tried using "action=" in the form and even calling window.location once Ajax completed to route to the next page. Every time the result is cleared. I've tried using factory with get/set, but this too clears the data on the second page after the window.location call.
Here's the factory code:
myApp.factory('searchService', function(){
var searchService = {};
var mySearchResult = {};
searchService.set = function(searchResult){
mySearchResult = searchResult;
}
searchService.get = function(text){
return mySearchResult;
}
return searchService;
});
CONTROLLER
myApp.controller('OnlineCVController', function($scope, searchService) {
$scope.searchPerson = function(personString) {
$.ajax({
url: "mySearch.php",
type: 'POST',
data: { Person: personString },
async: false, success: function (result) { searchService.set(result);
console.log(result);
window.location = "search.html";
}, error: function (result) { } });
}
Can anyone guide me further?

Angular Material: autocomplete not working without cache with $resource response

So it's basically what the question says, i have a function that returns a response from $resource which fetches from server.
var user = $resource(apiHost + '/users/:action/:query', {query: '#query'}, {
search: {
method: 'GET',
isArray: true,
params: {
action: 'search',
query: '#query'
}
}
});
self.search = function(name){
return user.search({query: name}, function(result){
return result;
});
}
these functions are inside a service, i say this just to clear some confusions
now, in controller, where i am making the call to service function
$scope.searchUser = function(name){
return userService.search(name);
};
it seems simple, but i have to admit i don't find any problem this far.
now in html where autocomplete is rendered
<md-autocomplete md-no-cache="true" md-search-text="searchText" md-selected-item="selectedItem" md-items="user in searchUser(searchText)" md-item-text="user.name">
<span md-highlight-text="searchText">{{user.name}}</span>
</md-autocomplete>
now from here. i am not sure if the problem comes from here. but when i type something in autocomplete, nothing shows.. and i have been making sure the server is getting the requests i need to make.
I have tried without the attribute md-no-cache and the effects are kind of different. When some text is entered. nothing is shown.. but when part of the text is deleted, the autocomplete shows the results.
You try to return the promise of your ngResource call in your searchUser() function:
$scope.searchUser = function(name){
return userService.search(name).$promise;
};

How to initialize array before $scope will be loaded in AngularJS application

I have problem with my AngularJS application. In my html view, i have list that contains JavaScript objects.
<div ng-init="initWeek()" ng-controller="TableController">
<div id="TaskImages"> <div ng-repeat="task in taskList"> <div id="TaskImg" ><br> {{task.title}}<br>{{task.start}} </div> </div></div>
I set taskList by using the Jquery/Ajax, which gets all task object from server.
function getTaskFromServer() {
$.ajax({
type : "POST",
url : "main_page",
success : function(data) {
var taskList = $.parseJSON(data);
week[0].push(taskList[0]);
},
});
My controller looks like this:
$scope.initWeek = function() {
getTaskFromServer();
};
$scope.taskList = week[currentlySelectedDay-1];
When I load application, the list "week" contains objects but in html view can see text.
I think that $scope.taskList is loaded before list "week".
For example, when I use:
$scope.initWeek = function() {
getTaskFromServer();
alert(week[0].lenght);
};
$scope.taskList = week[currentlySelectedDay-1];
Site displays alert and when i click Ok the text from taskList is a an website.
Since it is an asynchronous operation, you must set the taskList inside the ajax callback:
function getTaskFromServer() {
$.ajax({
type : "POST",
url : "main_page",
success : function(data) {
var taskList = $.parseJSON(data);
week[0].push(taskList[0]);
$scope.taskList = week[currentlySelectedDay-1];
},
});
}
It would be even better if you could replace the jquery ajax call with an angular call using $http.
Hope that helps.

Resources