Store and retrieve correct data - angularjs

I want to create a form for selecting a number of receiving then that's the reference items store correctly and retrieve correctly.
this is my angular js code
$scope.addreciveditemtemp = function(receiving,newreciveditemtemp) {
$scope.receiving_item = [ ];
$http.get('api/reciveditem').success(function(response) {
$scope.receiving_item = response;
for (var i=0;i<$scope.receiving_item.length;i++){
var receiving_item = $scope.receiving_item[i];
if(receiving_item.receiving_id===receiving.id){
console.log(receiving_item);
$http.post('api/reciveditemtemp', {
recived_id: receiving_item.receiving_id,
item_id: receiving_item.item_id,
cost_price: receiving_item.cost_price,
prequantity: receiving_item.quantity,
pretotal_cost: receiving_item.total_cost,
realtotal: receiving_item.total_cost
}).success(function(data, status, headers, config) {
$scope.reciveditemtemp.push(data);
$http.get('api/reciveditemtemp').success(function(data) {
$scope.reciveditemtemp = data;
});
});
}
}
});
};
this is my laravel controller code
public function store()
{ $this->newItem();
}
public function newItem()
{
$receiving_item = ReceivingItem::where('receiving_id', Input::get('item_id'))->get();
foreach($receiving_item as $value)
{
$reciveditemtemps = new reciveditemtemp;
$reciveditemtemps->recived_id = $value->receiving_id;
$reciveditemtemps->item_id = $value->item_id;
$reciveditemtemps->cost_price = $value->cost_price;
$reciveditemtemps->prequantity = $value->quantity;
$reciveditemtemps->pretotal_cost = $value->total_cost;
$reciveditemtemps->realquantity = $value->quantity;
$reciveditemtemps->realtotal = $value->cost_price * $value->realquantity;
$reciveditemtemps->save();
//return $ReceivingTemps;
}
return $reciveditemtemps;
}
But console answer is correct
how to solve this problem?? please help me.

This looks sketchy:
ERRONEOUS
}).success(function(data, status, headers, config) {
$scope.reciveditemtemp.push(data);
$http.get('api/reciveditemtemp').success(function(data) {
$scope.reciveditemtemp = data;
});
});
To push a value to an array and then replace the entire array does not seem right.

change the controller code.
public function newItem()
{
$reciveditemtemps = new reciveditemtemp;
$reciveditemtemps->recived_id = Input::get('receiving_id');
$reciveditemtemps->item_id = Input::get('item_id');
$reciveditemtemps->cost_price = Input::get('cost_price');
$reciveditemtemps->prequantity = Input::get('prequantity');
$reciveditemtemps->pretotal_cost = Input::get('pretotal_cost');
$reciveditemtemps->realtotal = Input::get('realtotal');
$reciveditemtemps->realquantity = Input::get('prequantity');
$reciveditemtemps->save();
return $reciveditemtemps;
}

Related

Cordova.writefile function doesn't run, but doesn't give an error

I'm making an ionic application. I have a function called scope.win() that's supposed to fire when a quiz is finished, and then update the JSON file to add that quiz to the number of finished quizzes but it doesn't run properly.It doesn't give off any error. The function just stops running at a certain point and the app keeps going and nothing is happening.
This is the controller's file
angular.module('controllers', ['services'])
.controller('MainCtrl', function ($scope, $state, data) {
$scope.$on('$ionicView.enter', function () {
data.create();
});
$scope.chapter = data.chapterProgress();
})
.controller("BtnClick", function ($scope, lives, data, $cordovaFile, $ionicScrollDelegate) {
var live = 3;
var clickedOn = [];
var numQuestions;
$scope.part2Cred = false;
$scope.part3Cred = false;
$scope.part4Cred = false;
$scope.part5Cred = false;
$scope.part6Cred = false;
$scope.part7Cred = false;
$scope.part8Cred = false;
$scope.part9Cred = false;
$scope.part10Cred = false;
$scope.partQCred = false;
$scope.setNumQuestions = function(num){
numQuestions = num;
}
$scope.updatelives = function (){
//grabs the element that is called liv then updates it
var livesOnPage = document.getElementById('liv');
livesOnPage.innerHTML = live;
}
$scope.wrong = function (event){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "grey";
clickedOn.push(selec);
live = live - 1;
if(live == 0){
$scope.gameover();
}
else{
$scope.updatelives();
}
}
}
$scope.right = function (event,chapter, section){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "green";
clickedOn.push(selec);
numQuestions = numQuestions - 1;
if(numQuestions === 0){
$scope.win(chapter, section);
}
}
}
$scope.gameover = function(){
alert("game over please try again");
live = 3;
$ionicScrollDelegate.scrollTop();
$scope.partQCred = false;
$scope.part1Cred = !$scope.part1Cred;
for(i = 0; i< clickedOn.length;i++){
clickedOn[i].style.color = "rgb(68,68,68)";
}
}
$scope.win = function (chapter, section) {
alert("Well Done");
var data = data.chapterProgress(); // It is at this point that the //function stops running without giving off any error.
alert("Good Job");
var sectionsComplete = data[chapter].sectionsCompleted;
var totalsection = data[chapter].totalSections;
if (section === totalSection) {
window.location.href = "#/chapter1sections";
return;
}
if (section > sectionsComplete) {
data[chapter].sectionsCompleted += 1;
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
document.addEventListener('deviceready', function () {
$cordovaFile.writeFile(url + "js/", "chapters.json", data, true)
.then(function (success) {
// success
alert("Json file updated")
window.location.href = "#/chapter1sections";
}, function (error) {
// error
});
});
}
}
});
Here is the Services file. It seems to run fine but it is referenced a lot in the problematic sections of code in the controllers so I figured it was necessary to put it here.
angular.module('services', [])
.service('lives', function () {
var live = 3;
return {
getlives: function () {
return live;
},
setlives: function (value) {
live = value;
}
};
})
.service('data', function ($cordovaFile, $http) {
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
return {
//Run this function on startup to check if the chapters.json file exists, if not, then it will be created
create: function () {
var init = {
"one": {
"sectionsCompleted": 0,
"totalSections": 4
},
"two": {
"sectionsCompleted": 0,
"totalSections": 1
}
};
$cordovaFile.writeFile(url + "js/", "chapters.json", init, false)
.then(function (success) {
// success
}, function (error) {
// error
});
},
chapterProgress: function () {
return $http.get(url + "js/chapters.json").success(function (response) {
var json = JSON.parse(response);
return json;
}, function (error) {
alert(error);
});
}
}
});
Thank You so much for the help and time.

Angular ng-file-upload Get Byte Array and FormData in Asp.net MVC

I am trying to use ng-file-upload to upload files using Angular. I need the byte array to store in our database (I cannot store the uploaded file on the server), but I also need the FormData as well. My problem is that I can only seem to get one or the other (either the byte array or the formdata) but not both.
Here is my Angular code:
$scope.uploadPic = function (file) {
$scope.emrDetailID = 7;
file.upload = Upload.upload({
url: '/SSQV4/SSQV5/api/Document/UploadEMRDocument',
method: 'POST',
data: { file: file, 'emrdetail': $scope.emrDetailID}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
$scope.imageID = file.result;
});
});
};
Using the code below, I can get the byte array and store it in my database:
public async Task<IHttpActionResult> UploadDocument()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
string ClientIP = IPNetworking.GetIP4Address();
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var extension = Path.GetExtension(filename).TrimStart('.');
var buffer = await f.ReadAsByteArrayAsync();
FileImageParameterModel pm = new FileImageParameterModel();
pm.binFileImage = buffer;
//pm.CompanyID = UserInfo.intMajorID;
pm.CompanyID = 10707;
pm.dteDocumentDate = Convert.ToDateTime("4/4/2016");
pm.dteExpiration = Convert.ToDateTime("4/4/2017");
pm.vchUserIP = ClientIP;
pm.vchUploadedbyUserName = UserInfo.Username;
pm.vchFileExtension = extension;
CommonClient = new CommonWebApiClient();
CommonClient.AuthorizationToken = UserInfo.AccessToken;
int imageID = await CommonClient.InsertNewFileImage(pm);
return Json(imageID);
}
else
{
return BadRequest("Attachment failed to upload");
}
}
Using the code below I can get the FormData
var provider = new MultipartFormDataStreamProvider(workingFolder);
await Request.Content.ReadAsMultipartAsync(provider);
var emr = provider.FormData["emrdetail"];
but then I can't get the byte array as using MultipartFormDataStreamProvider wants a folder to store the file.
There's got to be a way to get both. I have been searching the internet for 2 days and all I can find are the two solutions above neither of which solves my issue.
Any assistance is greatly appreciated!
You are thinking way to complicated. Here is some of my code which I used for file upload in AngularJS with .NET
Angular:
function uploadFileToUrl(file) {
var formData = new FormData(); // Notice the FormData!!!
formData.append('uploadedFile', file);
return $http({
url: uploadUrl,
method: 'POST',
data: formData,
headers: {
'Content-Type': undefined
}
}).then(resolve, reject);
function resolve(data) {
$log.debug('data : ', data);
return data;
}
function reject(e) {
$log.warn('error in uploadFileToUrl : ', e);
return $q.reject(e);
}
}
Server:
public Task HandleAsync([NotNull] UploadFilesCommand command)
{
return wrapper.InvokeOnChannel(async client =>
{
// init command
command.Output = new Dictionary<string, int>();
try
{
foreach (var file in command.Files)
{
var request = new UploadFileRequest
{
FileName = file.Name,
FileStream = file.Stream
};
UploadFileResponse response = await client.UploadFileAsync(request);
command.Output.Add(file.Name, response.Id);
}
}
finally
{
// dispose streams
foreach (var file in command.Files)
{
if (file.Stream != null)
{
file.Stream.Dispose();
}
}
}
});
}

implementing socket.io on existing application

My current application poll using MEAN stack and in controller I have a function vote() and API route defined as follow:
"/api/polls/pollID/pollChoiceID"
(ex. http://localhost:3001/api/polls/5587ad060a9e110816f9f1a8/5587ad060a9e110816f9f1a9)
I have the app working fine as it's but now I'm looking to implement socket.io on this app so that when client #2 connected and vote the voting result graph of client #1 will update in real time. I did some research about socket.io but I'm still stuck on implementing it.
For instance, in controller.js and inside the vote() I need to add:
socket.emit('send:vote', poll);
and over the routes/index.js I'll need to handle the socket.emit from controller so I wrap existing router.post codes with socket.on :
socket.on('send:vote', function(data){
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
//existing code here
}
}
However, Ii'm not sure if I'm taking the right steps so that they will work with my existing API route. Any inputs would be great! Thanks
/*
controller.js
*/
var voteObj = { poll_id1: pollSelected, choice1: pollChoiceSelected };
$scope.votedPollID = voteObj.poll_id1;
$scope.votedPollChoiceID = voteObj.choice1;
$scope.vote = function()
{
$http.post('/api/polls/' + $scope.votedPollID + '/' + $scope.votedPollChoiceID)
.success(function (data)
{
console.log(data);
$scope.poll = data;
})
.error(function(data) {
console.log('Error: ' + data);
})
/*
routes/index.js
*/
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
var testpollid = req.params.poll_id2;
var testpollchoiceid = req.params.poll_choice2;
var ipCounter = 0;
PollModel.findById({_id: req.params.poll_id2}, function(err, poll)
{
if(poll)
{
var choice = poll.choices.id(testpollchoiceid);
choice.votes.push({ ip: ip });
var ipCounter = ipCounter++;
poll.save(function(err, doc)
{
if(err)
{
return (err);
}
else
{
var theDoc = {
question: doc.question, id: doc._id, choices: doc.choices,
userVoted: false, totalVotes: 0
};
for(var i = 0, ln = doc.choices.length; i< ln; i++)
{
var choice = doc.choices[i];
for(var j= 0, jLn = choice.votes.length; j< jLn; j++)
{
var vote = choice.votes[j];
theDoc.totalVotes++;
theDoc.ip = ip;
if(vote.ip === ip)
{
theDoc.userVoted = true;
theDoc.userChoice = { _id: choice._id, text: choice.text };
}
}
}
poll.userVoted = theDoc.userVoted;
}
});
return res.json(poll);
}
else
{
return res.json({error:true});
}
});
});
});
});

Unable to get my data from $firebaseObject using AngularFire in a controller. View/ng-repeat works fine

I have different sections in Firebase with normalized data, and I have routines to get the information, but I cannot loop through the returned records to get data. I want to use the keys in the $firebaseArray() to get data from other $firebaseObject().
GetOneTeam() .... {
var DataRef = GetFireBaseObject.DataURL(Node + '/'); // xxx.firebaseio.com/Schedules/
var OneRecordRef = DataRef.child(Key); // Schedule Key - 1
return $firebaseObject(OneRecordRef);
}
...
var Sched = GetOneSchedule('Schedules', 1);
... // For Loop getting data - Put in HomeId
var TeamRec = GetOneTeam('Teams', HomeId);
var Name = TeamRec.TeamName; // Does not TeamName value from Schedule/1
The following is more of the actual code in case the snippet above is not clear enough. Sample common routine for getting data:
angular.module('MyApp')
.constant('FIREBASE_URL', 'https://xxxxxxxx.firebaseio.com/');
angular.module('MyApp')
.factory('GetFireBaseObject', function(FIREBASE_URL) {
return {
BaseURL: function() {
return new Firebase(FIREBASE_URL);
},
DataURL: function(Node) {
return new Firebase(FIREBASE_URL + Node);
}
};
}
);
// Common code for getting Array/Object from Firebase.
angular.module('MyApp')
.factory("FireBaseData", ["$firebaseArray", "$firebaseObject", "GetFireBaseObject",
function($firebaseArray, $firebaseObject, GetFireBaseObject) {
return {
AllRecords: function(Node) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
return $firebaseArray(DataRef);
},
OneRecordAllChildren: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var ParentRecordRef = DataRef.child(Key);
return $firebaseArray(ParentRecordRef);
},
OneRecord: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var OneRecordRef = DataRef.child(Key);
return $firebaseObject(OneRecordRef);
},
AddRecord: function(Node, Record) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var AddRecordRef = DataRef.child(Record.Key);
AddRecordRef.update(Record);
return $firebaseObject(AddRecordRef); // Return Reference to added Record
},
DeleteRecord: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var DeleteRecordRef = DataRef.child(Key);
DeleteRecordRef.remove();
}
};
}
]);
Individual Controller's retrieval of records from firebase.io:
angular.module('MyApp').service("ScheduleData", ["FireBaseData",
function(FireBaseData) {
var DataPath = 'Schedules';
this.AllSchedules = function() {
return FireBaseData.AllRecords(DataPath);
};
this.AddSchedule = function(GameInfo) {
return FireBaseData.AddRecord(DataPath, GameInfo);
};
this.DeleteSchedule = function(GameKey) {
FireBaseData.DeleteRecord(DataPath, GameKey);
};
this.GetOneSchedule = function(GameKey) {
return FireBaseData.OneRecord(DataPath, GameKey);
};
}
]);
// Structure of a record, including named fields to come from another object (Team/Venue using the OneRecord FireBaseData call to get a $firebaseObject
angular.module('MyApp').factory("ScheduleRecord", function() {
return {
Clear: function(GameInfo) {
GameInfo.Key = "";
GameInfo.HomeTeamId = "";
GameInfo.HomeTeamName = "";
GameInfo.AwayTeamId = "";
GameInfo.AwayTeamName = "";
GameInfo.VenueId = "";
GameInfo.VenueName = "";
GameInfo.GameDate = "";
GameInfo.GameTime = "";
}
};
}
);
Controller module start:
angular.module('MyApp').controller('ScheduleCtrl', ["$scope", "ScheduleData", "ScheduleRecord", "TeamData", "VenueData",
function ($scope, ScheduleData, ScheduleRecord, TeamData, VenueData) {
var ClearEditData = function() {
$scope.ScheduleEditMode = false;
ScheduleRecord.Clear($scope.schedule);
};
var GameSchedules = ScheduleData.AllSchedules();
This next piece is where my question lies. Once the promise returns the static schedule list, I want to loop through each record and translate the Team Id (Home/Away) and Venue Id to the names.
GameSchedules.$loaded().then(function() {
angular.forEach(GameSchedules, function(GameInfo) {
var HomeTeam = TeamData.GetOneTeam(GameInfo.HomeTeamId);
GameInfo.HomeTeamName = HomeTeam.Name;
The GetOneTeam returns a $firebaseObject, based on the HomeTeamId child record. This returns null all the time.
This is the TeamData.GetOneTeam return using the FireBaseData as well.
angular.module('MyApp').service("TeamData", ["FireBaseData",
function(FireBaseData) {
var DataPath = 'Teams';
this.AllTeams = function() {
return FireBaseData.AllRecords(DataPath);
};
this.AddTeam = function(TeamInfo) {
return FireBaseData.AddRecord(DataPath, TeamInfo);
};
this.DeleteTeam = function(TeamKey) {
FireBaseData.DeleteRecord(DataPath, TeamKey);
};
this.GetOneTeam = function(TeamKey) {
return FireBaseData.OneRecord(DataPath, TeamKey);
};
}
]);
As I have a Firebase Object, how can I get my named data objects from the $firebaseObject?
This is a mess. Use $firebaseArray for collections, not $firebaseObject. Most of these strange wrapper factories are unnecessary. AngularFire services already have methods for add, remove, and so on, and all these factories attempt to make AngularFire into a CRUD model and don't actually provide any additional functionality or enhancements.
app.factory('Ref', function(FIREBASE_URL) {
return new Firebase(FIREBASE_URL);
});
app.factory('Schedules', function($firebaseArray, Ref) {
return $firebaseArray(Ref.child('Schedules'));
});
// or if you want to pass in the path to the data...
//app.factory('Schedules', function($firebaseArray, Ref) {
// return function(pathToData) {
// return $firebaseArray(Ref.child(pathToData));
// };
//});
app.factory('Schedule', function($firebaseObject, Ref) {
return function(scheduleId) {
return $firebaseObject(Ref.child('Schedules').child(scheduleId));
}
});
app.controller('...', function(Schedules, Schedule, Ref) {
$scope.newSchedule(data) {
Schedules.$add(data);
};
$scope.removeSchedule(key) {
Schedules.$remove(key);
};
$scope.updateSchedule(key, newWidgetValue) {
var rec = Schedules.$getRecord(key);
rec.widgetValue = newWidgetValue;
Schedules.$save(rec);
};
// get one schedule
var sched = Schedule(key);
sched.$loaded(function() {
sched.widgetValue = 123;
sched.$save();
});
});

How to properly retrieve a record by ID

In my Angular/WebAPI app I'm struggling with retrieving a specific record by its id.
On the Front-End I have a controller and a data service. The controller calls a method on the data service, and the data service makes $http call to a WebAPI.
In my controller I'm passing the OID of the desired record to the getServiceRequestById method of the data service. Once of my issues is, that the actual value of that OID comes out as :1 instead of just 1.
My other issue is, that when the data service makes a call to WebAPI, the WebAPI perceives the request, as if it caries no ID in it, and passes that request onto its Get() method, instead of Get(int Id).
Here is my Front-End controller:
angular.module('frontEndApp').controller('EditServiceRequestCtrl',['$scope', 'requestsRepository','$routeParams',
function ($scope, requestsRepository,$routeParams) {
console.log("This is EditServiceRequestCtrl ; $routeParams: " + $routeParams);
//First we make a call to the data service, to fetch our ServiceRequest by its OID
//Then, in the callback function, we populate the $scope models below with the data of our retreived ServiceRequest
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
var Id = getCleanId();
//var cleanId = id.substring(0, 2);
console.log('getCleanId Id: ' + Id);
requestsRepository.getServiceRequestById(Id, function (request) {
$scope.OID = request.OID;
$scope.RequestorName = request.RequestorName;
$scope.RequestorBusinessUnit = request.RequestorBusinessUnit;
$scope.CustomerName = request.CustomerName;
$scope.CscContactPerson = request.CscContactPerson;
$scope.IsWbsCodeAvailable = request.IsWbsCodeAvailable;
$scope.SalesforceIdNumber = request.SalesforceIdNumber;
$scope.ProjectCtv = request.ProjectCtv;
$scope.RequestedCompletionDate = request.RequestedCompletionDate;
$scope.ToBeUsedForCloudMigration = request.ToBeUsedForCloudMigration;
$scope.ToBeUsedForDatacenterMove = request.ToBeUsedForDatacenterMove;
$scope.ToBeUsedForServerRefresh = request.toBeUsedForServerRefresh;
$scope.DataRequirements = request.DataRequirements;
$scope.DataProtectionRequirements = request.DataProtectionRequirements;
$scope.ProjectedDataAvailability = request.ProjectedDataAvailability;
$scope.DiscoveryLeadName = request.DiscoveryLeadName;
$scope.SelectedCountries = request.SelectedCountries;
$scope.ManualDiscovery = request.ManualDiscovery;
$scope.AutomatedDiscovery = request.AutomatedDiscovery;
$scope.DataLoadUsingMasterTemplate = request.DataLoadUsingMasterTemplate;
$scope.DataLoadUsingAutomatedInterface = request.DataLoadUsingAutomatedInterface;
$scope.DataLoaderRequiresSitizenship = request.DataLoaderRequiresSitizenship;
$scope.countries = [
{
name: "US", checked: false
},
{
name: "UK", checked: false
},
{
name: "France", checked: false
},
{
name: "Germany", checked: false
},
{
name: "Sweden", checked: false
},
{
name: "Danmark", checked: false
}
];
var list = [];
$scope.checkit = function () {
for (var p in $scope.countries) {
if ($scope.countries[p].checked) {
list.push($scope.countries[p].name);
console.log("selected country: " + $scope.countries[p].name + " " + $scope.ProjectedDataAvailability);
}
} return list;
}
console.log('EditServiceRequestCtrl $scope.RequestorName : ' + $scope.RequestorName);
});
$scope.updateServiceRequest = function () {
var ServiceRequest = {
requestorName: $scope.RequestorName,
requestorBusinessUnit: $scope.RequestorBusinessUnit,
customerName: $scope.CustomerName,
cscContactPerson: $scope.CscContactPerson,
isWbsCodeAvailable: $scope.IsWbsCodeAvailable,
salesforceIdNumber: $scope.SalesforceIdNumber,
projectCtv: $scope.ProjectCtv,
requestedCompletionDate: $scope.RequestedCompletionDate,
projectedDataAvailability: $scope.ProjectedDataAvailability,
toBeUsedForCloudMigration: $scope.ToBeUsedForCloudMigration,
toBeUsedForDatacenterMove: $scope.ToBeUsedForDatacenterMove,
toBeUsedForServerRefresh: $scope.ToBeUsedForServerRefresh,
dataRequirements: $scope.DataRequirements,
dataProtectionRequirements: $scope.DataProtectionRequirements,
selectedCountries:
list.filter(function (itm, i, a) {
return i == a.indexOf(itm);
}).toString(),
projectedDataAvailability: $scope.ProjectedDataAvailability,
discoveryLeadName: $scope.DiscoveryLeadName,
manualDiscovery: $scope.ManualDiscovery,
automatedDiscovery: $scope.AutomatedDiscovery,
dataLoadUsingMasterTemplate: $scope.DataLoadUsingMasterTemplate,
dataLoadUsingAutomatedInterface: $scope.DataLoadUsingAutomatedInterface,
dataLoaderRequiresSitizenship: $scope.DataLoaderRequiresSitizenship
};
requestsRepository.updateServiceRequest(ServiceRequest);
}
}]);
Here is my Front-End data service:
frontEndApp.factory('requestsRepository',function ($http) {
var createServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "POST", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("createServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("createServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var updateServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "PUT", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("updateServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("updatetServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var getServiceRequests = function (successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
}).success(function (data, status, headers, config) {
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
var getServiceRequestById = function (Id,successCallback) {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests/' + Id
}).success(function (data, status, headers, config) {
console.log("getServiceRequestById, data: " + data);
successCallback(data);
}).error(function (data, status, headers, config) {
return status;
});
};
return {
createServiceRequest: createServiceRequest, getServiceRequests: getServiceRequests,
updateServiceRequest: updateServiceRequest, getServiceRequestById: getServiceRequestById
};
});
And here is my Back-End WebAPI:
public HttpResponseMessage Get()
{
var requestList = from req in new XPQuery<DummyRequest>(uow) select req;
List<AccountViewServiceRequest> dataList = new List<AccountViewServiceRequest>();
foreach(var item in requestList)
{
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
dataList.Add(sr);
}
var response = Request.CreateResponse(HttpStatusCode.OK, dataList.ToList());
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
public HttpResponseMessage Get(int Oid)
{
var item = (from req in new XPQuery<DummyRequest>(uow) where req.Oid == Convert.ToInt32(Oid) select req).First();
AccountViewServiceRequest sr = new AccountViewServiceRequest();
sr.OID = item.Oid;
sr.RequestorName = item.RequestorName;
sr.RequestorBusinessUnit = item.RequestorBusinessUnit;
sr.CustomerName = item.CustomerName;
sr.CscContactPerson = item.CscContactPerson;
sr.IsWbsCodeAvailable = item.IsWbsCodeAvailable;
sr.SalesforceIdNumber = item.SalesforceIdNumber;
sr.ProjectCtv = item.ProjectCtv;
sr.RequestedCompletionDate = item.RequestedCompletionDate;
sr.ToBeUsedForCloudMigration = item.ToBeUsedForCloudMigration;
sr.ToBeUsedForDatacenterMove = item.ToBeUsedForDatacenterMove;
sr.ToBeUsedForServerRefresh = item.ToBeUsedForServerRefresh;
sr.DataRequirements = item.DataRequirements;
sr.SelectedCountries = item.SelectedCountries;
sr.DataProtectionRequirements = item.DataProtectionRequirements;
sr.ProjectedDataAvailability = item.ProjectedDataAvailability;
sr.DiscoveryLeadName = item.DiscoveryLeadName;
sr.ManualDiscovery = item.ManualDiscovery;
sr.AutomatedDiscovery = item.AutomatedDiscovery;
sr.DataLoadUsingMasterTemplate = item.DataLoadUsingMasterTemplate;
sr.DataLoadUsingAutomatedInterface = item.DataLoadUsingAutomatedInterface;
sr.DataLoaderRequiresSitizenship = item.DataLoaderRequiresSitizenship;
var response = Request.CreateResponse(HttpStatusCode.OK, sr);
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
Which part should I correct to successfully retrieve a single e record based on its OID?
Since it appears that your first issue is related to this routine:
var getCleanId = function () {
return $routeParams.OID.substring(0, 2)
};
Change the substring starting position to 1 to remove the prepended colon.
var getCleanId = function () {
return $routeParams.OID.substring(1, 2)
};
That in turn should fix the issue with not getting a single record out of the web api. The web api is trying to find a matching function signature in the controller on the web server. The only parameter can't convert to an integer, so it uses the Get() instead of the Get(int Oid).

Resources