Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i correctly use angular $timeout service outside of a typescript constructor?

I'm trying to figure out how to correctly use the angular $timeout service with TypeScript - So that i can show a splash-screen-like-behavior when someone for example clicks on a "Log In"-button.

interface INavigationController {
        username: string;
        password: string;
        loggedIn: boolean;
        ready: boolean;
        signIn(): void;
        signOut(): void;
    }

    class NavigationController implements INavigationController {
        username: string;
        password: string;
        loggedIn: boolean;
        ready: boolean;

        static $inject = ['$timeout'];
        constructor(private $timeout: ng.ITimeoutService) {
            var vm = this;
            vm.username = this.username;
            vm.password = this.password;
            vm.ready = true;

            // The line below work just fine from within here - but i want the behavior
            // when someone clicks a button, not directly like this.
            // Remove vm.ready = true above, before...
            //$timeout(function () { vm.ready = true;}, 2200);}

        signIn() {
            if (!this.username || !this.password) {
                alert("You need to frickin enter som details, man!");
            } else {
                this.ready = false;
                this.$timeout(function () {
                    this.ready = true;
                }, 2200);
            }
        }

I have also tried to set the invokeApply?:boolean to true:

this.$timeout(function () {
    this.ready = true;
}, 2200, true);

- Without any success...

If i console.log(this.ready); from within the this.$timeout(function()... it will show me true after 2200ms, but it seems that the $apply() doesn't apply?

Would appreciate if someone could enlighten me in how to use the $timeout and other services like it, correctly - Preferably using the style-guide i'm aiming for i.e. using "controllerAs with vm" - John Papa

like image 481
XT_Nova Avatar asked Feb 12 '15 08:02

XT_Nova


2 Answers

this.$timeout(()=> {
                this.ready = true;
            }, 2200);

if you use function(){} pattern you don't have access to this (this is not the one you expect)

like image 143
lujcon Avatar answered Sep 22 '22 03:09

lujcon


The 'this' inside the timeout is the this of the timeout function. You need to define a variable outside to reference that scope (usually called 'that') and refer to it inside the timeout:

var that = this;
$timeout(function() {
     that.value ='eggs';
}, 2200);
like image 32
Peter Ashwell Avatar answered Sep 21 '22 03:09

Peter Ashwell