我如何在打字稿构造函数之外正确使用angular $ timeout服务?

时间:2015-02-12 08:24:26

标签: angularjs typescript

我正在试图弄清楚如何正确使用TypeScript的角度$ timeout服务 - 这样当有人点击“登录”按钮时,我可以显示类似于闪屏的行为。< / p>

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);
            }
        }

我还尝试将invokeApply?:boolean设置为true:

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

- 没有任何成功......

如果console.log(this.ready);中的this.$timeout(function()...我会在2200毫秒后显示true,但似乎$apply()不适用?

如果有人可以启发我如何正确使用$ timeout和其他类似服务,我将不胜感激 - 最好使用样式指南我的目标是使用“controllerAs with vm” - John Papa < / p>

3 个答案:

答案 0 :(得分:6)

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

如果您使用function(){}模式,则您无权访问thisthis不是您期望的那种)

答案 1 :(得分:3)

&#39; this&#39;超时内部是超时功能的这个。您需要在外部定义一个变量来引用该范围(通常称为&#39;那个&#39;)并在超时内引用它:

var that = this;
$timeout(function() {
     that.value ='eggs';
}, 2200);

答案 2 :(得分:0)

试试这个,交配

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