I'm new to angular and MEAN stack, and prior to this, I asked a question here:
Angular Routing ngRoute fails to pull my other HTML files
Basically, I didn't properly set my app routing and the solution is I have to modify my link to #! from #, and someone there said that it was caused by breaking change in Angular 1.6, before this I had a working implementation but it wasn't a proper one-page app since it didn't pull only the appropriate HTML of the app. Okay, so now I can view and navigate the app.
Then I ran into another problem when I tried to communicate with the app which supposedly registered me into the app, when I clicked on the button on my HTML page
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
I got an error on the console log, saying
Error: $http.post(...).success is not a function
at b.$scope.register (iotApp.js:73)
at fn (eval at compile (angular.js:15152), <anonymous>:4:144)
at e (angular.js:26673)
at b.$eval (angular.js:17958)
at b.$apply (angular.js:18058)
at HTMLFormElement.<anonymous> (angular.js:26678)
at bg (angular.js:3613)
at HTMLFormElement.d (angular.js:3601)(anonymous function) # angular.js:14324(anonymous function) # angular.js:10834$apply # angular.js:18063(anonymous function) # angular.js:26678bg # angular.js:3613d # angular.js:3601
This is the part of the code indicated by the console where the error is
app.controller('authController', function($scope, $http, $rootScope, $location){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
$http.post('/auth/login', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
});
I have read some of the other answers but most of them have accidentally put the dependency in the method parameters where the controller is already imported. It works fine when I use the Advanced REST Client, which is a chrome extension to manually send a register request, but not when I use the app. Any help or just general pointers would be appreciated. Thank you!
From the $http.post documentation:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Related
I am calling a Web Service which returns around 3000 records as data entries as HTML response & i am trying to read this response using angularJS.
Below is my AngularJS code i am using to call the service
angular.module('tabApp', ['ngSanitize'])
.controller('TabController', ['$scope', 'HttpService', function($scope, HttpService) {
$scope.tab = 0;
$scope.setTab = function(newTab){
$scope.tab = newTab;
$scope.loading = true;
HttpService.CallService('Service.php?id='+newTab,newTab, function (data) {
$scope.myText = data;
$('.count').show();
$("[id^=searchg]").show();
$('.results').show();
});
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
$scope.setTab1 = function(newTab1){
$scope.tab = newTab1;
$('.loaderImage').hide();
};
$scope.isSet1 = function(tabNum){
return $scope.tab === tabNum;
};
}])
.service('HttpService', ['$rootScope', '$http', function ($rootScope, $http) {
$rootScope.loading = true;
return {
CallService: function (url,tabnum, callback) {
$http({
method: "POST",
url: url,
data: {id: tabnum}})
.success(function (data, status) {
$('.loaderImage').hide();
callback(data, status);
}).error(function (data, status) {
$('.loaderImage').hide();
callback(status);
});
}
}
}]);
My problem is the browser hangs if the returned records are more than 1500. Please advise on how i can improve this.
Update:
My html code looks like this
<div ng-show="isSet(1)">
<div id=matches style="display:none"></div>
<input type=text id=searchg placeholder="Type to search..." style="display:none" />
<p class="preload" ng-bind-html="myText"></p>
</div>
As we can see it is the bulky data which you are trying to bind. In Future, it could be more bulky.
You should use the server side pagination and get only the number of records, what your pagination is.
Here is the JSFiddle link for the reference.
http://jsfiddle.net/dwahlin/3Kewg/
Hope this helps! CHEERS TO CODE! :)
As #Mohit Dixit suggested, you should prefer to do server side paging and request only active page records.
I would advise you to use smart table library for this. Here is the official website for same. They support paging(both server side and client side), filter and sorting in one go.
Please note that there are many library available for this purpose but I am suggesting this as I am using it from past few years.
I have a trouble with IE when ng-click is used in the button.
I want to reload the data from spring controller whenever user click on the button which is working fine in chrome but not in IE11.
Issue is when page is loaded data is displayed on the webpage, when Refresh Data button is clicked, it will reload the data by hitting to the spring controller which is not working in IE. In IE, when user click on a button, it is hitting the angular controller as well as service method also but not hitting the spring controller.But when developer tools is opened it is hitting the spring controller.
Example below:
html code:
<div ng-controller="loadingSampleCtrl">
<button class="btn btn-primary" type="button" ng-click="loadOrRefreshData()">Reload</button>
{{myData.empName}} /* This is printed in chrome as well as in IE with developer tools opened*/
</div>
js code:
myApp.controller('loadingSampleCtrl', function ($scope, MyService) {
$scope.loadData = function () {
$scope.loading = true;
MyService.testData().then(
function (response) {
alert("response back from spring controllerf");
if(window.navigator.msSaveOrOpenBlob){
$scope.IEBrowser = true;
$scope.myData = response;
/* $timeout(function() {
$scope.pdfName = response;
}, 0);*/
} else {
$scope.IEBrowser = false;
$scope.myData = response;
}
},
function (errResponse) {
$rootScope.showError("Internal error" + errResponse);
});
}
$scope.testData();
});
//service call
_myService.testData = function(){
alert("service call");//this alert is visible in IE
var deferred = $q.defer();
var repUrl = myAppURL+'/myDataToRead/getData.form';
$http.get(repUrl).then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
deferred.reject(errResponse);
}
);
return deferred.promise;
}
spring controller:
#RequestMapping(value = "/getData", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
List<String> getMyData(HttpServletRequest request) throws Exception {
System.out.println("In MyDataController"); //not printed in IE when tested without developer tools
//logic here
//return statement
}
Any suggestions would be helpful.
i check you url var repUrl = yAppURL+'/myDataToRead/getData.form';, and i this the issue is you are not map controller with the path. you are only map your method with /getData. you need to use #RequestMapping annotation into your controller. you can refer below code :
#RestController
#RequestMapping("/myDataToRead")
I am building a small Angular and Node app. I have a form that a user inserts a email, then gets sent to the Node back-end, providing the credentials prove correct a 200 response code is passes to the Angular side. I now want to start a session if 200 response and set a variable to true to use on front-end to enable a div to use ng-hide or ng-show (will hold a button eventually).
So in summary
If 200 response generate a session or cookie and also set a var to true to enable ng-show or ng-hide.
Question
I am generation a variable that i am passing to the scope
$scope.LoginCorrect = true;
However my html side I have 2 div's that should respond depending on the scope variable LoginCorrect but are not responding ... so first question is why ?
Am I generating the cookie correct ?
Angular controller
This is where I set the variable and the cookie if 200 response code
FirstModule.controller('LoginController', function ($scope, $http) {
$scope.formData = {};
$scope.LoginForm = function () {
var data = {
LoginEmail: $scope.sometext.LoginEmail
};
$http({
url: 'http://localhost:8080/back-end/controller',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
}).then(function (response) {
if (response.status === 200)
$scope.sometext = "You are a valid member, please proceed to Mock Up Maker";
$cookies.put(data); // set cookie
$scope.LoginCorrect = true; // set variable to true for use in ng-show
}).catch(function (response) {
if (response.status === 400)
$scope.sometext = "Hmm, it seems you are not registered, try again or register";
else if (response.status === 404)
$scope.sometext = "this is non a valid email address, please check email";
else if (response.status === 500)
$scope.sometext = "No API connection. Server side fail ";
else $scope.sometext = "Server connection error, give it a second to establish connection then try again";
});
}
});
Angular view
Here I have ng-hide and ng-show divs that are not responding on the var passed to the scope
<form class="col-sm-8 col-sm-offset-2"
ng-controller="LoginController"
ng-submit="LoginForm()">
<div>
<div class="form-group">
<label>Email*</label>
<input type="email" class="form-control col-sm-12" name="LoginEmail" placeholder="Enter valid E-mail"
ng-model="sometext.LoginEmail">
<p>{{ sometext }}</p>
</div>
<input type="submit">
</div>
</form>
<div ng-hide="LoginCorrect">
hide when logged in
</div>
<div ng-show="LoginCorrect">
show when signed in
</div>
I am building a web application in Angular ( Im new to Angular).
I building a form to pass new user info to the third party software via API end point.
to post data I need to pass name(new user) email(new user) user_key(mine) and api_key (changes evry hour)
To get the new api_key I need to Post
POST: https://pi.pardot.com/api/login/version/3
message body: email=<email>&password=<password>&user_key=<user_key>
and this returns
<rsp stat="ok" version="1.0">
<api_key><api_key here></api_key>
</rsp>
Once I have the new Key I can pass it with the form post to post data.
Question
I think Ill need to have a function that runs before the Posting of data that dose the post to get the new api_keyand changes the api_key variable on my new user post.
so the main question is how do I do this with angular, I have added my current post controller bellow that post the new user data.
My controller
// submit button controller POST
// =============================================================================
FirstModule.controller('formController', function ($scope, $http) {
$scope.formData = {};
$scope.processForm = function (Fname, Lname, email) {
var data = {
Fname: $scope.formData.Fname,
Lname: $scope.formData.Lname,
email: $scope.formData.email,
api_key: 'changes every hr', //needs to be dynamic
user_key: 'my key'
};
//Call the services
$http.post('https://some api.com/api/prospect/version/4/do/create', JSON.stringify(data)).then(function (response) {
if (response.data)
$scope.formData = "Post Data Submitted Successfully!";
}, function (response) {
$scope.formData = "Post Data Submitted Failed";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
My form
<form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2"
ng-submit="processForm()"
ng-click="postdata(formData)">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</form>
So this part is Ok, but how do I run a function before this runs so I get the latest api_key ? and more importantly how can I do it safe ?
The API is Pardot
For security should I place all; API request on a backed script maybe node ?
you can try to use app.run() and write the function in that. app.run() will always run before your controller. Here is one link you can check AngularJS app.run() documentation?
I am learning how to use angular javascript alongside my favorite, PHP framework (CodeIgniter). I have a login section that authenticates to a service and gets the response using angular js. The code works fine. See snippet below
var login = angular.module('authenticationApp' , ['ngMaterial' , 'ngRoute']) ;
login.controller('authenticationController', function ($scope, $http) {
$scope.authenticate = function () {
if ($scope.username == undefined || $scope.password == undefined) {
$scope.login_error_message = "All form fields are required" ;
} else {
var url = get_base_url() + 'student/authentication/login?username=' + $scope.username + '&password=' + $scope.password ;
$http.post(url).then(
function (response) {
console.log(response) ;
/*Here I handle success*/
}, function (response) {
$scope.login_error_message = "Service Error!. Response: " + response ;
}
) ;
}
} ;
My problem is how can I send that response to the success.php page and also redirect to the success page. I can redirect using
window.location.href = get_base_url() + 'administrator/authentication/dashboard' ;
My challenge now is actually sending the response to this new location.
Thanks in advance and I am ready to provide more details if need be
After battling for long, I just decided to use plain js. Crappy but works.