I have a problem with getting request in my api from Angular.js. After i loged in to my app I keep the username in $rootScope.currentuser,
$rootScope.$on('$routeChangeStart', function () {
if (Auth.isLoggedIn()) {
app.isLoggedIn = true;
Auth.getUser().then(function (data) {
$rootScope.currentuser = data.data.username;
app.username = data.data.username;
app.useremail = data.data.email;
app.loadme = true;
});
} else {
app.isLoggedIn = false;
app.username = '';
$rootScope.currentuser = '';
app.loadme = true;
}
});
then I call the middleware:
$http.get('/api/costs/' + $rootScope.currentuser).then(function (data) {
$scope.costs = data.data;
});
to get specific costs for current user, unfortunetelly this get request doesn't work, I checked $rootScope.currentuser right after login and this value is assigned properly. What is curious, when I manualy assigned in user name middleware
$http.get('/api/costs/' + 'test').then(function (data) {
$scope.costs = data.data;
});
the date is populated.
Related
Here is the controller of angular js that is calling the service to get the hotels
vm.getTopHotels = function(){
var hotelsLimit = 10;
var top_hotels =
dataService.getHotels()
.then(function(hotels){
console.log('adf');
sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC');
hotelDetailsCheck = checkDetailsIfExists(sortHotels);
//Get only top 10 hotels for home page
top_hotels = hotelDetailsCheck.slice(0,10);
vm.topHotels = top_hotels;
},
function(data){
console.log('Failed to get Hotels');
});
};
vm.getTopHotels();
** And here is the dataService that is calling the Http get request to get the data but in the controller, it gives me undefined so is there something wrong in the datsService return method because I think it is not returning **
(function(){
angular
.module('app')
.factory('dataService',DataFactory);
DataFactory.$inject = ['$http','$q']
function DataFactory($http,$q){
var service = {
hotels:[],
getHotels:getHotels,
saveHotels:saveHotels
};
return service;
function saveHotels(){
var def = $q.defer();
$http.get('/hotels/saveHotelsData')
.then(function successCallback(data){
def.resolve(data);
},function errorCallback(data){
def.reject('Something went down :(');
});
return def.promise;
}
function getHotels(){
// var def = $q.defer();
return $http.get('/hotels/getHotelsData')
.then(function successCallback(data){
service.hotels = data;
});
}
}
})();
// ...
.then(function(data) {
console.log('adf');
sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC');
What's hotels? It isn't declared anywhere. If hotels is supposed to be the response from API, then it should be declared so:
.then(function(hotels) {
console.log('adf');
sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC');
Update: your getHotels passes results through a function without return statement, hence will resolve to undefined. Should be
function getHotels(){
return $http.get('/hotels/getHotelsData')
.then(function successCallback(data) {
service.hotels = data;
return data;
});
}
i dont understand why it is always pop-up the 1st alert no matter what i input it right or wrong. Can you help me take a look at my code and show me what i have done wrong. Thank you very much.
<script>
var myapp = angular.module('myapp', []);
myapp.controller('Alerts', function getAlerts($scope, $http) {
$scope.name = null;
$scope.host = null;
$scope.searchs = [];
$scope.hide = false;
$scope.getSearch = function(name, host) {
$scope.hide = $scope.hide = true;
var data = {
name: name,
host: host
};
var url = "https://h2kgcp144d.execute-api.us-east-2.amazonaws.com/Testing-midterm/rds-search-alert-info";
$http.post(url, data)
.then(
function(response) {
$scope.searchs = angular.fromJson(response.data);
alert('Alerts found!');
//$scope.hide = false;
},
function(error) {
alert('Failed to search!');
//$scope.search = false;
});
};
});
</script>
You set the alert on both success and failure case. If this is what you want, then remove the alert from the success case:
function(response) {
$scope.searchs = angular.fromJson(response.data);
//$scope.hide = false;
},
So, I have a button that triggers a javascript function, that calls an AJAX request, that calls an actionresult that should update my database.
Javascript Call
function changeDepartment() {
// Initiate and value variables,
var id = $('#requestId').val();
var user = $('#contactUser').val();
// Bind variables to data object
var data = { id: id }
// Ajax call with data.
$.ajax({
url: '#Url.Action("changeDepartmentActionResult", "ManageRequestResearch")',
type: "POST",
dataType: 'json',
data: data,
success: function (data, textStatus, XmlHttpRequest) {
var name = data.name;
window.location.href = '#Url.Action("Index", "ManageRequestResearch")';
$('#btn-input').val('');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("responseText: " + jqXHR.responseText);
}
});
alert(data);
And then, I have the action result:
[HttpPost]
public ActionResult changeDepartmentActionResult(string id)
{
var moadEntities = new MOADEntities();
moadEntities.Configuration.AutoDetectChangesEnabled = false;
var researchBusiness = new ResearchRequestBusiness(moadEntities);
var request = researchBusiness.FetchRequestById(Convert.ToInt32(id));
var directoryObject = GetActiveDirectoryObject(request.Requestor);
var requstorDisplayName = directoryObject != null ? directoryObject.DisplayName : request.RequestorFullName;
var researchRequestFileBusiness = new ResearchRequestFilesBusiness(moadEntities);
var requestFiles = researchRequestFileBusiness.FetchFilesByRequestId(Convert.ToInt32(id));
var viewModel = new ManageSelectedRequestResearchViewModel()
{
RequestDetails = request,
RequestActivity = request.tbl_ResearchRequestActivity.Select(d => d).ToList(),
Files = requestFiles
};
moadEntities.Configuration.AutoDetectChangesEnabled = false;
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
return Json("Status changed successfully", JsonRequestBehavior.AllowGet);
}
From what I have observed, it returns the right record, it makes the changes properly, and it hits the Context.SaveChanges();
when debugging -- i can see before the save changes is made that the values have indeed changed, however--inside the database, no changes are saved.
In addition, i have checked to see that the connection strings are valid.
Any idea what may be causing this?
Thanks ahead of time!
It seems that you are modifying an entity while auto detecting changes are disabled.
If it is intentional then you should inform the context that the entity has been changed.
I assume that MOADEntities is derived from DbContext. So instead of this:
if (request.GovernmentEnrollment == true)
{
request.GovernmentEnrollment = false;
request.ManagedCare = true;
moadEntities.SaveChanges();
}
else
{
request.ManagedCare = false;
request.GovernmentEnrollment = true;
moadEntities.SaveChanges();
}
I would try this:
// Simplify the if..else block
request.ManagedCare = request.GovernmentEnrollment;
request.GovernmentEnrollment = !request.GovernmentEnrollment;
// Notifying the context that the 'request' entity has been modified.
// EntityState enum is under System.Data.Entity namespace
moadEntities.Entry(request).State = EntityState.Modified;
// Now we can save the changes.
moadEntities.SaveChanges();
I have made an IRC bot for purely learning purposes but I have a Minecraft server that I use an API to get the status back as JSON. Now I have made the code and it works but for some reason when I try and use a return on the function so I can get the content it seems to not work?
So I have the two functions below:
function getservers(name) {
if (name == "proxy") {
var Request = unirest.get(proxy);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
console.log(data["motd"]);
return data.motd;
});
} else if (name == "creative") {
var Request = unirest.get(creative);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
return data;
});
} else if (name == "survival") {
var Request = unirest.get(survival);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
return data;
});
}
}
// Main logic:
function parsemessage(msg, to) {
// Execute files
function pu(o,t,f){if(o)throw o;if(f)throw f;bot.say(to,t)}
if (msg.substring(0,1) == pre) {
// Get array
msgs = msg.split(' ');
console.log(msgs[0]);
// Run Login
if (msgs[0] == pre+"help") {
bot.say(to, "Help & Commands can be found here: https://server.dannysmc.com/bots.html");
} else if (msgs[0] == pre+"status") {
// Get status of server, should return online/offline - player count for each server - motd
server = getservers("proxy");
console.log(server);
/*var data = '';
var Request = unirest.get('https://mcapi.us/server/status?ip=185.38.149.35&port=25578');
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
});
} else if (msgs[0] == pre+"players") {
// Should return the player list for each server
} else if (msgs[0] == pre+"motd") {
// Should return the message of the day.
} else if (msgs[0] == pre+"ip") {
bot.say(to, "ShinexusUK IP Address: shinexusuk.nitrous.it");
} else if (msgs[0] == pre+"rules") {
}
}
}
The code in the getservers() function works, when I do the
console.log(data["motd"]);
It outputs my servers message of the day. But when I do return
data.motd
(same as data["motd"]?) The code that calls the function is here
server = getservers("proxy");
console.log(server);
Please note this is a node.js code and it contains many files so i can't exactly paste it. So here is the link to the github repo with the whole node application: Here
When the function getservers is called, it makes an asynchronous request and return nothing.
Then the callback is fired with the response of that request as parameter.
Note that the function getservers will end before the end callback of your request is called
(simplified version)
function getservers(name) {
var Request = unirest.get(proxy);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
console.log(data["motd"]);
return data.motd;
});
// nothing returned here
}
What you need is a function callback that will be called after you got the response.
function getservers(name, callback) { // callback added
var Request = unirest.get(proxy);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
console.log(data["motd"]);
callback(data.motd); // fire the callback with the data as parameter
});
// nothing returned here
}
And then you can use your function like this :
getservers("proxy", function(server){
console.log(server);
....
})
I'm really struggling with this because it should be very simple. I have a route with a controller defined called login. In my template I have the following data binding {{error}} which is defined in my controller after executing a method from a custom service, and resolving the returned promise.
Controller
app.controller("login", ['$scope','XMLMC', 'ManageSettings', function ($scope,api,ManageSettings) {
$scope.error = 'test';
$scope.login = function() {
var params = {
selfServiceInstance: "selfservice",
customerId: $scope.username,
password: $scope.password
};
var authenticated = api.request("session","selfServiceLogon",params).then(function(response) {
ManageSettings.set("session",response, $scope);
if(response.status === "ok") {
window.location.href = 'portal';
} else {
$scope.error = response["ERROR"];
console.log($scope.error);
}
});
};
}]);
The console shows Customer not registered. Showing that $scope.error has been updated appropriately, but the view never gets updated. My service is below, and please note that I am doing nothing "outside" of angular and so I should not have to $apply() anything manually.
app.factory("XMLMC", ['$http', '$q', function ($http, $q) {
function XMLMC($http, $q) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
var that= this;
this.prepareForPost = function(pkg) {
return JSON.stringify(pkg);
};
this.request = function(service, request, params, host, newsession) {
var def = $q.defer();
var P = def.promise;
if(request === "analystLogon") {
newsession = true;
}
var call = {
service: service,
method: request,
params: params
};
if(host) {
call.host = host;
} else {
call.host = "localhost";
}
if(newsession) {
call.newsession = "true";
}
var pkg = {
contents: this.prepareForPost(call)
};
$http.post('php/XMLMC/api.php', jQuery.param(pkg)).success(function (response,status) {
that.consume(response, def);
}).error(function (response,status) {
def.reject(response,status);
});
return P;
};
this.consume = function(response, defer) {
console.log(response);
var resp = response[0],
digested = {},
i;
digested.status = resp["attrs"]["STATUS"];
var params = resp["children"][0]["children"];
for(i=0; i < params.length; i++) {
var key = params[i]["name"];
var val = params[i]["tagData"];
digested[key] = val;
}
defer.resolve(digested);
//return digested;
};
}
return new XMLMC($http, $q);
}]);
I've created a plunk here with the code exactly as it is on my test server. The routes and etc aren't working for obvious reasons, but you can at least see the code and how it works together
http://plnkr.co/edit/AodFJfCijsp2VWxWpbR8?p=preview
And here is a further simplified plunk where everything has one scope and one controller and no routes. For some reason, this works in the plunk but the $http method fails in my server
http://plnkr.co/edit/nU4drGtpwQwFoBYBfuw8?p=preview
EDIT
Even this fails to update
var authenticated = api.request("session","selfServiceLogon",params).then(function(response) {
ManageSettings.set("session",response, $scope);
$scope.error = "foo!";
if(response.status === "ok") {
window.location.href = 'portal';
}
});
It appears that $scope.$apply is indeed needed. See AngularJS - why is $apply required to properly resolve a $q promise?
To quote #pkozlowski.opensource:
In AngularJS the results of promise resolution are propagated asynchronously, inside a $digest cycle. So, callbacks registered with then() will only be called upon entering a $digest cycle.