简体   繁体   中英

How to redirect in Angular 1.5?

Complete beginner to AngularJs, how do I redirect to a certain page in this service method?

The destination should be "/#/login", I've tried with $location and $window but I might very well be missing something.

Thanks

 angular.module('app.services', ['ngRoute'])
    .service('TaskPlannerApiService', [
        '$http', '$q', '$timeout', function taskPlannerApiService($http, $q, $timeout) {
            var me = this;

            me.getDataAsync = function () {

                var logincheck = true;
                var apiCall = $q.defer();
                var timeoutHanlder = $timeout(function () {
                    apiCall.reject('Timed out');
                    console.log('timed out');
                }, 2000);

                $http.get('/api/login/check').success(function (chk) {
                    console.log(chk);
                    logincheck = chk;
                    console.log(logincheck);

                    if (chk === false) {
                        logincheck = false;
                    }

                    if (logincheck == true) {
                        console.log("/api/taskplanner");
                        $http.get('/api/taskplanner/').success(function (data) {
                            $timeout.cancel(timeoutHanlder);
                            apiCall.resolve(data);
                            console.log(data);
                        }).error(function (data) {
                            $timeout.cancel(timeoutHanlder);
                            apiCall.reject(data);
                            console.log(data);
                        });
                    }
                    else {
                        console.log("redirect");
                    }
                })

                $timeout(function () { apiCall.notify('Retrieving Data . . .'); }, 0);
                return apiCall.promise;
            };
        }
    ])

$location Inject this your controller

Next, if you want the place to use the below code.

$location.path('/login');

If you are using angularjs internal routes than you have to inject $location in your controller and give this code below.

  $location.path( "/login" );

If you are using ui-router which is quite famous in angularjs then you will be dealing with states. so in such case you have to inject $state in controller and change your state using this:

$state.go('state name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM