How to redirect to other page after successful log

2019-07-24 06:19发布

问题:

Hi I am developing one application in angularjs as front end and web api2 as backend. I am new to both angular and web api. I have completed login page in angularjs. As soon as my login successful i want to go to page called Index.cshtml located at Views/Home/index.cshtml. I am trying as below.

This is my controller code.

app.controller('Login', function ($scope, LoginService) {
    $scope.Login = function () {
        var sub = {
            User_Name: $scope.User_Name,
            User_Password: $scope.User_Password
        };
        var checkData = LoginService.Login(sub);
        checkData.then(function (data) {
            //want redirection
            var url = '/Home/Index/';
            window.location = url;
            }, function (error) {
            })
        };
});

This is my module.js

var app;
(function () {
    app = angular.module("Login", []);
})();

service.js

app.service("LoginService", function ($http) {
    this.Login = function (sub) {
        var credentials = { User_Name: sub.User_Name, User_Password: sub.User_Password };
           $http.post('api/NCT_UsersLogin/', credentials).success(function (response) {  });
    }
});

I am trying using window.location but it is not working. May I get some help here? Any help would be appreciated. Thank you.

回答1:

Try this,

 $window.location.href = '/Home/index.html';

also inject $window to your controller

app.controller('Login', function ($scope, LoginService,$window) {
    $scope.Login = function () {
        var sub = {
            User_Name: $scope.User_Name,
            User_Password: $scope.User_Password
        };
        var checkData = LoginService.Login(sub);
        checkData.then(function (data) {
            //want redirection        
              $window.location.href = '/Home/index.html';
            }, function (error) {
            })
        };
});


回答2:

You can use $state.go(url)

Try this

app.controller('Login', function ($scope, LoginService, $state) {
    $scope.Login = function () {
        var sub = {
            User_Name: $scope.User_Name,
            User_Password: $scope.User_Password
        };
        var checkData = LoginService.Login(sub);
        checkData.then(function (data) {
            //want redirection
            var url = '/Home/Index/';
            $state.go(url);
            }, function (error) {
            })
        };

});



回答3:

Try to change this:

window.location = url;

in this:

window.open("http://www.example.com","_self");

You should redirect correctly.



回答4:

You need to use $state.go('/home');

For ex:

     $http.post('api/NCT_UsersLogin/', credentials).success(function (response) { 
      //if your response status is success then redirect to another page using 
        $state.go('/home');
     });