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
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With