I have a factory in which I set a IP which is common for all controllers. I get the ip in the other controllers and add the web service method like this: url : $scope.ipForHttp+"getDeviceDetailsReport" where $scope.ipForHttp is http://websitename.com/ which I get from the factory.
This works in my local computer. When I host this and open the page I get it the first time for all pages. But when I refresh the page I see an error in console.
GET http://websitename.com/undefinedgetDeviceDetailsReport 404 (Not Found). I get this error only when I refresh the page and only in the hosted site, not in my local computer.
I'm getting undefined between the / and method name getDeviceDetailsReport.
This is some of the code where I use the data from factory:
$scope.ipForHttp = userDetailsFactory.getUserDetailsFromFactory().ipAddress;
$scope.loading = false;
$scope.ClientID = userDetailsFactory.getUserDetailsFromFactory().clientidFromSession;
// $scope.dev={};
$scope.getDevice =function(){
$scope.loading = true;
$http({
method : "GET",
url : $scope.ipForHttp+"getDeviceDetailsReport" //i think undefined error here.
And I'm getting this Error: ngRepeat:dupes
Duplicate Key in Repeater too only when I refresh the page.
Edit. I run the factory and set the value every time the page is refreshed. Maybe the value is undefined the second time..but I don't know how I still have the old value.
Maybe this is why I get the Error: ngRepeat:dupes when I refresh too. What am I doing wrong?
The index page's(which contains the other html pages) controller with the factory:
angular.module('tollApp')
.controller('indexController', function($scope,$http,$window,userDetailsFactory){
$scope.usernameFromServer={};
$scope.getUserDetails = function(){
$http({
method:'GET',
url:'http://192.168.1.80:4000/getUserDetails'
// url:'http://websitename.com/getUserDetails'
})
.then(function(response){
// console.log(JSON.stringify(response));
userDetailsFactory.setUserDetailsInFactory(response.data);
$scope.usernameFromFactory = userDetailsFactory.getUserDetailsFromFactory().usernameFromSession;
$scope.theIP = userDetailsFactory.getUserDetailsFromFactory().ipAddress;
// $scope.usernameFromServer = userDetailsFactory.getUserDetailsFromFactory().username;
// console.log(JSON.stringify($scope.usernameFromFactory)+"usernameFromFactory");
})
}
$scope.logout = function(request,response){
$http({
method:'GET',
url:'/logout'
})
.then(function(response){
console.log(JSON.stringify(response));
if(response.data=="logout"){
// $window.location.href="http://websitename.comlogin";
$window.location.href="http://192.168.1.80:4000/login";
}
})
}
console.log("indexController");
}).factory('userDetailsFactory',function(){
var user = {};
return {
setUserDetailsInFactory : function(val){
user.useridFromSession = val[0].UserID;
user.usernameFromSession = val[0].UserName;
user.userroleFromSession = val[0].UserRole;
user.clientidFromSession = val[0].ClientID;
user.ipAddress = "http://192.168.1.80:4000/";
// user.ipAddress = "http://websitename.com/";
// console.log("in set "+user.clientidFromSession);
},
getUserDetailsFromFactory : function(){
return user;
}
};
});
That error is because you are doing an ng-repeat on a collection with duplicates. You need to track by index when you are doing an ng-repeat on a collection with duplicates.
Related
I am passing an array of values through POST method dynamically.
If i pass more than 50 array values, i am not able to process those data.
I am getting error 505.
I browsed and found that it is an Http error, which refers the post size is not good here.
So i added the properties in my jboss configuarion,
</system-properties>
<property name="org.apache.tomcat.util.http.Parameters.MAX_COUNT" value="-1"/>
</system-properties>
Even after this, i am not able to pass array value more than 50.
Please give some solution for this.
This is my code, in Restfull webservice, where i get data from angular controller.
this.updateConstraint = function($scope, $location, $routeParams) {
var url = hostName + "/dcr/rest/capacityfile/searchcf/blockC/addSubFilesBlocC";
var listSubFiles = $scope.capacityAddSubFile;
var idCapacity = $routeParams.capacityFileId;
var promise = $http({
url : url,
method : "POST",
params :{ subFileCSF : $scope.capacityAddSubFile,
partConstraint : $scope.selectedPartNumberAndConstraint,
partConstraintAdd : $scope.selectedPartNumberAndConstraintAdd,
capacityFileId : $routeParams.capacityFileId},
}).success(function(data, status, headers) {
}).error(function(data, status, headers) {
// alert("Failed to access"+status+" "+headers);
});
return promise;
};
Here the i am getting error, it is showing error 505.
Please reply.
you need to set max-post-size at connector level.
/subsystem=web/connector=http:write-attribute(name=max-post-size, value=80)
Please find below the angularjs factory method to call http request:
var HttpService = angular.module("HttpService",[]);
HttpService.factory("HttpServiceFactory",['$http', '$q', '$location', '$rootScope' ,function($http, $q, $location, $rootScope){
return {
getData: function(url, headers, bOnErrorRedirect, bShowInPageError, params){
var headerParam = {'Accept':'application/json'};
if(headers !== undefined || headers !== null){
headerParam = $.extend(headerParam, headers);
}
var updatedParams = {'TimeStamp':new Date().getTime()};
updatedParams = $.extend(params, updatedParams);
var deferred = $q.defer();
$http.get(url,{
headers: headerParam,
params : updatedParams
}).success(function(successResponse){
if(successResponse){
var responseJSON = angular.fromJson(successResponse);
if(responseJSON && responseJSON.messages && responseJSON.messages.length){
//Process Error
}else{
deferred.resolve(successResponse);
}
}else{
deferred.resolve(successResponse);
}
}).error(function(errorResponse , status){
//Process Error
console.error("status here:: "+status);
});
return deferred.promise;
}
}
}]);
And I am calling this method in controller with all required dependencies as below:
HttpServiceFactory.getData(args.sURL,null,false,true,args.oQueryParams).then(function(response){
scope.bDataLoading = false;
// process data
})
.catch(function(oResponse) {
scope.bDataLoading = false;
scope.bDisplayError = true;
// process error
});
Here everything works fine. But the issue is when I've multiple http calls on a page, the UI freezes and does not allow to interact till the request has been processed.
For example, on a page I am displaying 2 angular-ui-grid based on user's selected criteria by input box and calendar control. In such case, the UI freezes until both grids have been displayed or error message has been displayed.
During http service call, user can not do anything but simply wait to finish the request.
How do I resolve the issue of UI freezing ? Is it a true async behavior ? If not, what am I missing to achieve correct async behavior ?
I'm developing a single page application. I am making use of Angularjs.v1.2.28. I'm making a HTTP GET request to the backend using this code.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http.get(req);
},
I make use of the promise object that is returned from service in controller.
var categoryPromise = categoryService.getCategories(sessionid,terminalid,tableno,section);
categoryPromise.then(function(payload){
var categories = payload.data;
if(categories.status.code == "1"){
if(Object.prototype.toString.call(categories) === '[object Array]') {
$scope.categories = categories;
categoryService.setCategories(categories);
$scope.pax = tableService.getPax();
$scope.tablechair = tableService.getChoseTableChair();
}
}
else{
$location.url("/login");
$scope.errorMsg = categories.status.desc;
}
},function(errorPayload){
$location.url("/login");
$scope.errorMsg = "Server error while processing the request.Please contact system administrator";
});
It's always the errorCallback is getting called due to the URL getting changed to the browser application URL appended with some malformed characters. The URL which i give is
http://localhost:8080/CafexRestful/menucategories
But, it gets changed to the browser application URL below
http://localhost:8080/CafexMobile/[object%20Object]
I have been debugging in Chrome and Firebug. I couldn't resolve it. It may be something which is happening under the hood. The same code is working with another controller and service, where i fetch a different data. Please let me know if you need anymore information. Thanks.
$http.get in angularjs needs an url string. You should use url string instead of an object
Using $http.get function:
return {
getCategories : function(){
return $http.get("/menucategories"); // using $http.get function.
},
Using $http function.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http(req); //using $http function only.
},
Please see the document: https://docs.angularjs.org/api/ng/service/$http
I have built a simple application in Angular consuming a simple API I created myself using Laravel. The application is hosted here. The API is hosted here. Now I can log in to the application at which point the API returns a simple auth_token which is sent as the URL parameter in every subsequent request that is sent to the server.
There is only one user in the system:
Email: admin#admin.com
Password: admin12345
You can log into the application using these credentials at which point the application will set a cookie using the $cookieStore service and will use the token in this cookie for every subsequent request. After using the application, a user can log out from the application, where a DELETE request is sent to the server and on the success method, the cookie is deleted from the browser.
Unfortunately there is some issue with the code I suppose. The DELETE request is working as expected and it deletes the auth_token on the server and returns 200 OK. But the success method is not called. I am not sure what I am doing wrong. It might be just a syntax problem.
app.js
function AppCtrl ($scope, $cookieStore, $location, Auth) {
$scope.setActive = function (type) {
$scope.destinationsActive = '';
$scope.flightsActive = '';
$scope.reservationsActive = '';
$scope[type + 'Active'] = 'active';
};
$scope.authenticate = function (credentials) {
Auth.save(credentials, function(data){
$cookieStore.put('auth_token', data.auth_token);
$scope.isLoggedIn = true;
$location.path('destinations');
$scope.message = null;
}, function(data){
$scope.message = "Email/Password combination incorrect!";
});
};
$scope.logout = function () {
//var auth_token = $cookieStore.get('auth_token');
Auth.delete({
'auth_token': $cookieStore.get('auth_token')
}, function(data){
$scope.isLoggedIn = false;
$cookieStore.remove('auth_token');
});
};
if($cookieStore.get('auth_token')){
$scope.isLoggedIn = true;
}else{
$scope.isLoggedIn = false;
}
}
The logout function is called when the log out button is pressed. What am I doing wrong here?
Note: The application is not working on Chrome for some reason (Use Firefox). If you can shed some light on that, it would be very helpful.
Both the repositories are public if you wish to have a look:
AngulAir Application: http://gitlab.learningtechasia.com:8901/rohan0793/angulair.git
AngulAirAPI: http://gitlab.learningtechasia.com:8901/rohan0793/angulairapi.git
Here is your solution
$scope.logout = function () {
//var auth_token = $cookieStore.get('auth_token');
Auth.delete(
{'auth_token': $cookieStore.get('auth_token')}, // parameters
{},//postData, which you don't need for this
function(data){
$scope.isLoggedIn = false;
$cookieStore.remove('auth_token');
},
// error callback
function (httpResponse) {
// do what you want for error handling here
}
);
};
Note:-> (Below points solved the problem)
Only the 2nd option(postdata) in $resource.delete API was missing. We should give it as a blank {} if it is not required for API.
And delete method should return 204 Status Code in order to execute success callback.
I can't see what the problem with this is.
I'm trying to fetch data on a different server, the url within the collection is correct but returns a 404 error. When trying to fetch the data the error function is triggered and no data is returned. The php script that returns the data works and gives me the output as expected. Can anyone see what's wrong with my code?
Thanks in advance :)
// function within view to fetch data
fetchData: function()
{
console.log('fetchData')
// Assign scope.
var $this = this;
// Set the colletion.
this.collection = new BookmarkCollection();
console.log(this.collection)
// Call server to get data.
this.collection.fetch(
{
cache: false,
success: function(collection, response)
{
console.log(collection)
// If there are no errors.
if (!collection.errors)
{
// Set JSON of collection to global variable.
app.userBookmarks = collection.toJSON();
// $this.loaded=true;
// Call function to render view.
$this.render();
}
// END if.
},
error: function(collection, response)
{
console.log('fetchData error')
console.log(collection)
console.log(response)
}
});
},
// end of function
Model and collection:
BookmarkModel = Backbone.Model.extend(
{
idAttribute: 'lineNavRef'
});
BookmarkCollection = Backbone.Collection.extend(
{
model: BookmarkModel,
//urlRoot: 'data/getBookmarks.php',
urlRoot: 'http://' + app.Domain + ':' + app.serverPort + '/data/getBookmarks.php?fromCrm=true',
url: function()
{
console.log(this.urlRoot)
return this.urlRoot;
},
parse: function (data, xhr)
{
console.log(data)
// Default error status.
this.errors = false;
if (data.responseCode < 1 || data.errorCode < 1)
{
this.errors = true;
}
return data;
}
});
You can make the requests using JSONP (read about here: http://en.wikipedia.org/wiki/JSONP).
To achive it using Backbone, simply do this:
var collection = new MyCollection();
collection.fetch({ dataType: 'jsonp' });
You backend must ready to do this. The server will receive a callback name generated by jQuery, passed on the query string. So the server must respond:
name_of_callback_fuction_generated({ YOUR DATA HERE });
Hope I've helped.
This is a cross domain request - no can do. Will need to use a local script and use curl to access the one on the other domain.