Estoy usando una llamada ajax para realizar la funcionalidad en un archivo de servicio y si la respuesta es exitosa, quiero redirigir la página a otra url. Actualmente, estoy haciendo esto usando js simples “window.location = response [‘message’];”. Pero necesito reemplazarlo con el código angularjs. He buscado varias soluciones en stackoverflow, usaron $ location. Pero soy nuevo en angular y tengo problemas para implementarlo.
$http({ url: RootURL+'app-code/common.service.php', method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, dataType: 'json', data:data + '&method=signin' }).success(function (response) { console.log(response); if (response['code'] == '420') { $scope.message = response['message']; $scope.loginPassword = ''; } else if (response['code'] != '200'){ $scope.message = response['message']; $scope.loginPassword = ''; } else { window.location = response['message']; } // $scope.users = data.users; // assign $scope.persons here as promise is resolved here })
Puedes usar Angular $window
:
$window.location.href = '/index.html';
Ejemplo de uso en un controlador:
(function () { 'use strict'; angular .module('app') .controller('LoginCtrl', LoginCtrl); LoginCtrl.$inject = ['$window', 'loginSrv', 'notify']; function LoginCtrl($window, loginSrv, notify) { /* jshint validthis:true */ var vm = this; vm.validateUser = function () { loginSrv.validateLogin(vm.username, vm.password).then(function (data) { if (data.isValidUser) { $window.location.href = '/index.html'; } else alert('Login incorrect'); }); } } })();
Puede redirigir a una nueva URL de diferentes maneras.
$location.path(YOUR_URL);
o $location.url(YOUR_URL);
. Entonces, la diferencia básica entre los 2 métodos es que $location.url()
también afecta los parámetros de obtención, mientras que $location.path()
no lo hace. Yo recomendaría leer los documentos en $location
y $window
para que pueda comprender mejor las diferencias entre ellos.
$location.path('/configuration/streaming');
esto funcionará … inyecta el servicio de ubicación en el controlador
Utilicé el siguiente código para redireccionar a una nueva página
$window.location.href = '/foldername/page.html';
e inyecté $ window object en mi función de controlador.
¡Puede ser que te ayude!
La muestra de código AngularJs
var app = angular.module('app', ['ui.router']); app.config(function($stateProvider, $urlRouterProvider) { // For any unmatched url, send to /index $urlRouterProvider.otherwise("/login"); $stateProvider .state('login', { url: "/login", templateUrl: "login.html", controller: "LoginCheckController" }) .state('SuccessPage', { url: "/SuccessPage", templateUrl: "SuccessPage.html", //controller: "LoginCheckController" }); }); app.controller('LoginCheckController', ['$scope', '$location', LoginCheckController]); function LoginCheckController($scope, $location) { $scope.users = [{ UserName: 'chandra', Password: 'hello' }, { UserName: 'Harish', Password: 'hi' }, { UserName: 'Chinthu', Password: 'hi' }]; $scope.LoginCheck = function() { $location.path("SuccessPage"); }; $scope.go = function(path) { $location.path("/SuccessPage"); }; }
En Angular Js puede redirigir su formulario ( en el envío ) a otra página usando windos.location.href = ”;
Me gusta esto:
postData(email){ if (email=='undefined') { this.Utils.showToast('Invalid Email'); } else { var origin = 'Dubai'; this.download.postEmail(email, origin).then(data => { ... }); window.location.href = "https://www.thesoftdesign.com/"; } }
Simplemente prueba esto:
window.location.href = "https://www.thesoftdesign.com/";
La manera simple que uso es
app.controller("Back2Square1Controller", function($scope, $location) { window.location.assign(basePath + "/index.html"); });
Una buena forma de hacerlo es usando $ state.go (‘statename’, {params …}) es más rápido y más amigable para la experiencia del usuario en los casos en que no tenga que volver a cargar y cargar toda la configuración de la aplicación y demás
(function() { 'use strict'; angular .module('app.appcode') .controller('YourController', YourController); YourController.$inject = ['rootURL', '$scope', '$state', '$http']; function YourController(rootURL, $scope, $state, $http) { $http({ url: rootURL + 'app-code/common.service.php', method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, dataType: 'json', data:data + '&method=signin' }).success(function (response) { if (response['code'] == '420') { $scope.message = response['message']; $scope.loginPassword = ''; } else if (response['code'] != '200') { $scope.message = response['message']; $scope.loginPassword = ''; } else { // $state.go('home'); // select here the route that you want to redirect $state.go(response['state']); // response['state'] should be a route on your app.routes } }) } });
// rutas
(function() { 'use strict'; angular .module('app') .config(routes); routes.$inject = [ '$stateProvider', '$urlRouterProvider' ]; function routes($stateProvider, $urlRouterProvider) { /** * Default path for any unmatched url */ $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', templateUrl: '/app/home/home.html', controller: 'Home' }) .state('login', { url: '/login', templateUrl: '/app/login/login.html', controller: 'YourController' }) // ... more routes .state } })();
Enfrenté problemas al redireccionar a una página diferente también en una aplicación angular
Puede agregar la $window
como Ewald ha sugerido en su respuesta, o si no desea agregar la $window
, simplemente agregue un tiempo de espera y ¡funcionará!
setTimeout(function () { window.location.href = "http://whereeveryouwant.com"; }, 500);
(function () { "use strict"; angular.module("myApp") .controller("LoginCtrl", LoginCtrl); function LoginCtrl($scope, $log, loginSrv, notify) { $scope.validateUser = function () { loginSrv.validateLogin($scope.username, $scope.password) .then(function (data) { if (data.isValidUser) { window.location.href = '/index.html'; } else { $log.error("error handler message"); } }) } } }());
Si quieres usar un enlace, entonces: en el html tienes:
en el archivo typescript
public openLineItems() { if (this.$stateParams.id == 0) { this.Flash.create('warning', "Need to save order!", 3000); return } this.$window.open('#/orderLineitems/' + this.$stateParams.id);
}
Espero que vea este ejemplo útil ya que fue para mí junto con las otras respuestas.