How to auto redirect after X seconds in AngularJS?

前端 未结 5 784
自闭症患者
自闭症患者 2021-01-17 22:24

What is the right way to do this in AngularJS? I didn\'t find any simple answer to this.

I\'d like to :

  1. Load a page
  2. Wait for X seconds
相关标签:
5条回答
  • 2021-01-17 22:52

    you can simply redirect to aby other component by this:

    open your filename.component.file and ADD this function

    $timeout(function() {
          $location.path('/login');
          }, 3000);
    
    });
    

    and your page will be redirect to login component after 3 second

    0 讨论(0)
  • 2021-01-17 22:54

    It does work also using $location instead of $state!

    JS

    app.controller('SeeYouSoonCtrl', function($scope, $location, $timeout) {
    
        $timeout(function() {
          $location.path('/nextsite');
          }, 3000);
    
        });
    
    0 讨论(0)
  • 2021-01-17 22:55

    If someone is looking for the same feature in angular 2 +.

    import { Router } from '@angular/router';
    
    constructor(private router: Router) {}
    
    ngOnInit() {
        // do init at here for current route.
    
        setTimeout(() => {
            this.router.navigate(['nextRoute']);
        }, 5000);  //5s
    }
    
    0 讨论(0)
  • 2021-01-17 23:08

    Basically, Their are two way $location and $timeout. This will solve your issue:

    1. By $timeout method :

    code :

      .controller('HomeController', ['$scope', '$state', '$timeout',
                                    function($scope, $state, $timeout) {    
       $timeout(function() {
          $state.go('anotherstate');
          }, 4000);
    
        }])
    
    1. By $location method :

    code:

    .controller('HomeController', ['$scope', '$state', '$location',
                                        function($scope, $state, $location) {    
          $location.path('/appurl');
    
            }])
    
    0 讨论(0)
  • 2021-01-17 23:12

    This works (thanks PSL):

    .controller('SeeYouSoonCtrl', ['$scope', '$state', '$timeout',
                                    function($scope, $state, $timeout) {
    
        $timeout(function() {
          $state.go('AnotherState');
          }, 3000);
    
        }])
    
    0 讨论(0)
提交回复
热议问题