Why "alert" always show the first one? - javascript

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;
},

Related

I'm trying to return some data from http request in angular js but it gives an undefined

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 keep getting this error "angular.js:TypeError: Cannot read property 'pages' of undefined"

The error in console after console.log(data)
var app = angular.module("myApp", []).config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist(['**']);
});
app.controller("myCtrl",["$scope","$window", "$http",
function($scope, $window, $http,) {
//variable to get input
var input = $('input');
var search = $("#search");
var form = $('form');
//Function for random wiki article
$scope.Random = function() {
$window.open("https://en.wikipedia.org/wiki/Special:Random", "_blank");
};
//function for searching wiki article
$scope.search = function() {
$scope.result = [];
var title = input.val();
var api = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=";
//var cb = "&callback=JSON_CALLBACK";
var page = "https://en.wikipedia.org/?curid=";
$http.jsonp(api + title, {jsonpCallbackParam: 'callback'}).then(function(data) { var results = data.query.pages;
console.log(data);
angular.forEach(results, function(v,k) {
$scope.results.push({title: v.title, body: v.extract, page: page + v.pageid})
})
});
};
}]);
This is my angular script.I have also used $scedelegateProvider to make the URL in white-list. It is used for calling the Wikipedia API.Help me please to resolve this issue.
I've tested like below and my result was fine.
CODE
var title = 'Angularjs';
var api = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
var url = $sce.trustAsResourceUrl(api+title);
$http.jsonp(url, {
headers: {
'Access-Control-Allow-Origin' : '*', // add this
'Content-Type': 'application/json'
}
}).then(function(data) {
console.log(data.data.query.pages);
});
CONSOLE
Try this. :)

Angular.js geting data from mongodb

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.

Update scope variable from $http.get on JSON

I'm having an issue with a $scope variable not updated :
In my controller I have :
$scope.frCartoList = [];
$scope.enCartoList = [];
$scope.cartoList = [];
$scope.filteredCartoList = [];
$scope.loadJSON = function () {
$http.get("SVG/fr/cartoList.json")
.success(function (data) {
$scope.frCartoList = data;
})
.error(function () {
console.log("Error while getting french json.");
});
$http.get("SVG/en/cartoList.json")
.success(function (data) {
$scope.enCartoList = data;
})
.error(function () {
console.log("Error while getting english json.");
});
$scope.setDefaultSearch();
$scope.getAreaFilters();
$scope.getBlockFilters();
if ($scope.shared)
$scope.homeVisible = false;
console.log($scope.enCartoList);
};
$scope.setJSON = function () {
if ($scope.isEnglish)
$scope.cartoList = $scope.enCartoList;
else if ($scope.isFrench)
$scope.cartoList = $scope.frCartoList;
console.log($scope.enCartoList);
$scope.initMenu();
$scope.filteredCartoList = $scope.cartoList.filter($scope.search);
};
$scope.loadJSON();
$scope.setJSON();
But my $scope.enCartoList and my $scope.frCartoList have the proper value only inside the $http.get
I suppose, this is not the main $scope that is used or something, but that's weird, because before that I had only one $scope.cartoList I used to set in the $scope.loadJSON and it was updated in the whole controller...

model not updating in .then method of promise angularjs

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.

Categories