How to redirect a page in angularjs - javascript

angular.module('myApp',[])
.controller('loginCtrl',function ($scope, $http, $rootScope, $location, $window{
$scope.login = function(loginData){
$scope.dataLoading = true;
$scope.loginData = angular.copy(loginData);
$http({
method : 'GET',
url : 'php/login.php',
params: {'email' : loginData.email,'password': loginData.password,'rand' : Math.random()}
}).then(function mySucces(response,$location){
$scope.dataLoading = false;
$scope.msg1 = response.data.msg1;
$scope.msg2 = response.data.msg2;
$scope.firstname = response.data.firstname;
$scope.flag = response.data.flag;
console.log($scope.flag);
$location.url('http://localhost/timetrake/welcome.html');
}, function myError(response) {
$scope.user = response.statusText;
});
}
});

You can use Angular $window:
$window.location.href = 'timetrake/welcome.html';
Then
$scope.dataLoading = true;
$scope.loginData = angular.copy(loginData);
$http({
method : 'GET',
url : 'php/login.php',
params: {'email' : loginData.email,'password': loginData.password,'rand' : Math.random()}
}).then(function mySucces(response,$location){
$scope.dataLoading = false;
$scope.msg1 = response.data.msg1;
$scope.msg2 = response.data.msg2;
$scope.firstname = response.data.firstname;
$scope.flag = response.data.flag;
console.log($scope.flag);
$window.location.href = 'timetrake/welcome.html';);
}, function myError(response) {
$scope.user = response.statusText;
});

$location.path('/timetrake/welcome.html');
Why dont you add welcome.html into a scope route config and so u can do '/timetrake/welcome'

Inject $location in your controller
For example
jimApp.controller('mainCtrl', function($scope, $location){
$location.url(".....")
});

Try this
$location.path('/timetrake/welcome.html');
I prefer you to use ng-route it gives you more flexibility and it maintain state for redirection and it can easily navigate by just
$state.go()

Related

How to create service and use it in controller

I am having a simple login form and I want to validate user upon successful HTTP request and it works fine. however, I've written all the code in the controller itself and I don't want that. i am new to angularjs so i have trouble creating service. so I need to create service for my logic. can anyone create service for the logic in the controller so that code works exactly same?
sample.html(for now it only prints username, password, and status code of response)
<html>
<head>
<script src="angular.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="mycontroller">
Username <input type="text" ng-model="login" /><br><br> Password <input
type="password" ng-model="pass" /><br>
<button type="submit" ng-click="myfunc()">Login</button>
<center>User name is {{ login }}, password is{{pass}}<br>
{{success.code}}
</div>
</body>
</div>
</body>
</html>
Controller
var app = angular.module("myapp", []);
app.controller("mycontroller", function($scope, $http, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
$http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: mydata
}).then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});
Super simple. First create a service, which injects $http module. Make a method you can call which returns promise from the $http module. In this example it's a get method.
app.service("ExampleService", function($http){
this.ExampleRequest = function(){
return $http.get('url');
}
});
Inject the service created above and you can call the functions you've defined in the service. Notice that the .then comes from the promise.
app.controller("exampleCtrl", function($scope, ExampleService){
$scope.onClick = function(){
ExampleService.ExampleRequest().then(function(data){
// Do something with data
});
}
});
Create a myService factory and create a function to send http req and return the response.
app.factory('myService', function($http) {
return {
httpReq: function(data) {
return $http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: data
})
}
}
});
Now call it from the controller.
app.controller("mycontroller", function($scope, myService, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
myService.httpReq(mydata)
.then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});

$state.go() doesn't change page until second login with refesh?

My project use angularJS 1.6.2
the problem is that user info is correct, but doesn't change page through $state.go(sidebar.overall);
But it chage page with twice login, and the second login with refresh page.
The first login is success with server,and has got the success response.
my login.js as following:
if($scope.loginForm.$valid) {
var postData = {
username : $scope.username,
password : $scope.loginForm.password.$modelValue,
smsCode : $scope.messageCode
};
$scope.method = "post";
$scope.url = BASE_URL + "/user/login/users";
$http({
method:$scope.method,
url: $scope.url,
data : postData,
headers : {
"Content-Type": 'application/json'
}
}).then( function (response, event) {
console.log(response);
event.preventDefault();
$state.go("sidebar.overall");
if(response.data.success == true){
$cookieStore.put("userMessage", response);
$state.go("sidebar.overall");
if($cookieStore.get('userMessage')){
$scope.uMessage = $cookieStore.get('userMessage');
$http({
method: 'GET',
url: BASE_URL + '/user/roles/privileges/parts/' + $scope.uMessage.data.data.user.roleId,
headers : {
"Content-Type": 'application/json'
}
}).then(function (res){
localStorage.setItem('permitInfo',JSON.stringify(res.data));
}, function(res){
console.log(res);
});
}
}
and app.js file :
.config(['$stateProvider', '$urlRouterProvider', '$httpProvider', function ($stateProvider, $urlRouterProvider, $httpProvider){
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
$urlRouterProvider.otherwise( function($injector, $location) {
var $state = $injector.get("$state");
$state.go("loginlogout");
});
}]).controller('RootController', ['$rootScope', '$scope', $timeout','$location', '$state', '$cookieStore', 'locals', function($rootScope, $scope, $timeout, $location, $state, $cookieStore, locals){
if($cookieStore.get('userMessage')){
$rootScope.userMessage = $cookieStore.get('userMessage');
console.log($rootScope.userMessage);
} else {
$state.go('loginlogout');
}
$rootScope.permitInfo = JSON.parse(localStorage.getItem('permitInfo'));
$scope.$on('$locationChangeStart',function(evt, next, previous) {
angular.element('#loading').modal('show');
});
$scope.$on('$locationChangeSuccess',function(evt, next, previous) {
angular.element('#loading').modal('hide');
angular.element(".modal").modal("hide");
});
$scope.$on('$stateChangeSuccess',function(evt, next, previous) {
angular.element('#loading').modal('hide');
angular.element(".modal").modal("hide");
});
$scope.$on('$viewContentLoaded',function(evt, next, previous) {
angular.element('input').attr("autocomplete", "off");
window.scrollTo(0,0);
angular.element(".modal-backdrop").hide();
});
angular.module('frontierApp.loginlogout', ['ui.router', 'ngCookies'])
.config(['$stateProvider', function($stateProvider){
$stateProvider
.state('loginlogout',{
url : '/login',
templateUrl: 'modules/loginlogout/login_view.html',
controller: 'LoginController'
})
}])
thanks for help.

Service factory not working

I inject this into my controller module:
var services = angular.module('services', []);
services.factory('jsonManager', ['$http', function($http) {
return{
loadData: loadData
}
function loadData(){
$http({
method: 'GET',
url: 'data/2015_data.json'
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return response.err;
});
}
}]);
... and it doesn't work! I'm using it on the controller like this, check it out:
var ctrls = angular.module('controllers', ['services']);
ctrls.controller('overviewController', ['jsonManager', '$scope',
function(jsonManager, $scope){
$scope.load = function(){
var datos = jsonManager.loadData();
console.log(datos);
$scope.gastos = datos.gastos.data;
$scope.ganancias = datos.ganancias.data;
}
I omitted some code from my controller; the scope objects work properly. The problem is, that I get an error that tells me that "datos" is undefined at lines 55 and 56. Why does this happen?
The $http service returns a promise, so you need to use then(successCallback, errorCallback) to resolve the promise.
service
var services = angular.module('services', []);
services.factory('jsonManager', ['$http', function($http) {
var loadData = function(){
$http({
method: 'GET',
url: 'data/2015_data.json'
});
return {
loadData: loadData
};
}]);
controller
var ctrls = angular.module('controllers', ['services']);
ctrls.controller('overviewController', ['jsonManager', '$scope', function(jsonManager, $scope){
$scope.load = function(){
var datos = jsonManager.loadData().then(function(res) {
console.log(res.data);
$scope.gastos = res.data.gastos.data;
$scope.ganancias = res.data.ganancias.data;
}, function(err) {
console.log(err);
});
};
}]);
$http is asynchronous and
console.log(datos);
$scope.gastos = datos.gastos.data;
is run before jsonManager.loadData(); return it's value
Use callbacks or a promises
function loadData(callback){
$http({
method: 'GET',
url: 'data/2015_data.json'
}).then(function successCallback(response) {
callback(null, response.data);
}, callback);
}
$scope.load = function(){
var datos = jsonManager.loadData(function(err, datos){
console.log(datos);
$scope.gastos = datos.gastos.data;
$scope.ganancias = datos.ganancias.data;
});
}
It is asynchronous, so one way would be to force it to resolve in $scope.load like this:
$scope.load = function(){
var datos = jsonManager.loadData().then(function(results){return results;});
console.log(datos);
$scope.gastos = datos.gastos.data;
$scope.ganancias = datos.ganancias.data;

TypeError: Cannot read property 'post' of undefined [duplicate]

This question already has an answer here:
Cannot read property 'get' of undefined with Angular
(1 answer)
Closed 8 years ago.
I'm getting the following error:
TypeError: Cannot read property 'post' of undefined
at postName (http://127.0.0.1:9000/scripts/controllers/main.js:28:12)
at Scope.$scope.submit (http://127.0.0.1:9000/scripts/controllers/main.js:10:7)
at http://127.0.0.1:9000/bower_components/angular/angular.js:10348:21
at http://127.0.0.1:9000/bower_components/angular/angular.js:18333:17
at Scope.$eval (http://127.0.0.1:9000/bower_components/angular/angular.js:12175:28)
at Scope.$apply (http://127.0.0.1:9000/bower_components/angular/angular.js:12273:23)
at Scope.$delegate.__proto__.$apply (<anonymous>:855:30)
at HTMLFormElement.<anonymous> (http://127.0.0.1:9000/bower_components/angular/angular.js:18332:21)
at HTMLFormElement.jQuery.event.dispatch (http://127.0.0.1:9000/bower_components/jquery/dist/jquery.js:4641:9)
at HTMLFormElement.elemData.handle (http://127.0.0.1:9000/bower_components/jquery/dist/jquery.js:4309:46) angular.js:9563(anonymous function) angular.js:9563(anonymous function) angular.js:7004Scope.$apply angular.js:12275$delegate.__proto__.$apply VM1976:855(anonymous function) angular.js:18332jQuery.event.dispatch jquery.js:4641elemData.handle
My main.js file:
'use strict';
angular.module('sayHiApp')
.controller('MainCtrl', function ($scope) {
// Accepts form input
$scope.submit = function() {
// POSTS data to webservice
postName($scope.input);
// GET data from webservice
var name = getName();
// DEBUG: Construct greeting
$scope.greeting = 'Sup ' + name + ' !';
};
function postName ($scope, $http, dataToPost) {
$http.post('/name', dataToPost).
success(function(data) {
$scope.error = false;
$scope.data = data;
}).
error(function(data) {
$scope.error = true;
$scope.data = data;
});
}
// GET name from webservice
function getName ($scope, $http) {
$http.get('/name').
success(function(data) {
$scope.error = false;
$scope.data = data;
return data;
}).
error(function(data) {
$scope.error = true;
$scope.data = data;
return 'error name';
});
}
});
I'm not sure what this error is referring to? If it's referring to the 'post' method on '$http' then I'm very confused.. Thanks in advance for any help :)
This is referring to the 'post' method on '$http' as you suggested.
You need to add $http as a parameter in the controller function so angular will inject it (just as you did with $scope).
I did another change to your code, removed the $scope and $http parameters from the inner functions as they are known in the function because of closure.
angular.module('sayHiApp')
.controller('MainCtrl', function ($scope, $http) {
// Accepts form input
$scope.submit = function() {
// POSTS data to webservice
postName($scope.input);
// GET data from webservice
var name = getName();
// DEBUG: Construct greeting
$scope.greeting = 'Sup ' + name + ' !';
};
function postName (dataToPost) {
$http.post('/name', dataToPost).
success(function(data) {
$scope.error = false;
$scope.data = data;
}).
error(function(data) {
$scope.error = true;
$scope.data = data;
});
}
// GET name from webservice
function getName () {
$http.get('/name').
success(function(data) {
$scope.error = false;
$scope.data = data;
return data;
}).
error(function(data) {
$scope.error = true;
$scope.data = data;
return 'error name';
});
}
});
the function postName doesn't need to have these vars passed to it
$scope, $http it only needs the dataToPost the other two vars are already accessible. Your function should just look like this
function postName (dataToPost) {
$http.post('/name', dataToPost).
success(function(data) {
$scope.error = false;
$scope.data = data;
}).
error(function(data) {
$scope.error = true;
$scope.data = data;
});
}

Can't cancel $interval in factory

I wrote a factory to long-poll, with start and stop methods. However, I can't cancel the timer. Any ideas?
app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) {
Poller.start(1, $scope.session.user.user_uuid, function(result) {
User.data.queues.montage_progress = result.field;
if (result.field == 100) {
Poller.stop(); //DOES NOT STOP (see below)
}
});
})
Here is the factory:
app.factory('Poller', function($http, $q, $interval, $window) {
var poll = this;
poll.timer = null;
poll.checkProgress = function(field, user_uuid) {
var deferred = $q.defer();
$http({
method: 'GET',
url: '/api/v1/poll/',
json: true,
params: {
field: field,
user_uuid: user_uuid
}
})
.success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject("Error checking poll");
});
return deferred.promise;
};
poll.start = function(url, user_uuid, callback) {
poll.timer = $interval(function() {
poll.checkProgress(url, user_uuid).then(function(result) {
console.log(result);
callback(result);
}, function(error) {
alert(error);
});
}, 2000);
};
poll.stop = function() {
$interval.cancel(poll.timer);
};
return poll;
});
EDIT:
Changed $window.clearInterval to $interval.cancel(poll.timer); as suggested below. But still can't cancel polling...
You should use the cancel method of $interval, not clearInterval
poll.stop = function() {
$interval.cancel(poll.timer):
};

Categories

Resources