简体   繁体   中英

angular $timeout after refresh

Iam having problems with angular $timeout. It works ok If I wont hit F5/reload page. When I reload the page the timeout stops and never calls the function I provided in timeout. I feel like the code is good but Iam missing something. Why the timeout is never hit when I refresh the page?

export class AccountController
{

    constructor(private $scope: ControllerScope, private $location: ng.ILocationService, private AuthService: AuthService, private $timeout: ng.ITimeoutService)
    {

    }

    public Login(model: LoginModel)
    {
        this.AuthService.login(model).then((response: any) =>
        {
            //when token will expire -> logout
            this.$timeout(() =>
            {
                this.Logout();
            }, <number>response.TokenExpireTime).then((d) =>
            {
                alert('Czas trwania sesji wygasł');
            });

            this.$location.path('/');
        },
        (err) =>
        {
            alert(err.error_description);
        });

    }

    public Logout()
    {
            this.AuthService.logOut();
            this.$location.path("/login");
    }

}

Well, assuming that you call LOGIN only once user clicks login button, here's the explanation.

When you register $timeout, it will be removed once you refresh your browser. This is standard behaviour and just the way it all works in browser environment.

That is - on a new page refresh, when user is already logged in, you no longer call login method. It means that you don't register your $timeout once again and after refresh, browser has no idea that you wanted to use it.

One solution might be to change that code to register $timeout on every page load but taking further look at your code, you can set TokenExpireTime as a variable inside eg localStorage and use it in somewhere else.

Example assuming localStorage['expires'] is set.

if (localStorage['expires']) {
   $timeout(function() {
      // do your thing, if you are not going to update model, keep 3rd parameter false,
      // otherwise skip it to prevent $digest cycle from running
   }, localStorage['expires'], false);
}

This is similar to bank sessions that logs you out after 15 minutes no matter what are you doing.

If you want to reset timeout when user goes to a different page or just interacts with your app, you need to make that logic slightly more advanced by adding eg focus events.

$(window).on('focusin', function() {
    // clear timeout, user is back in your app
});

$(window).on('focusout', function() {
   // register timeout, user is away
});

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