【问题标题】:How do i correctly use angular $timeout service outside of a typescript constructor?我如何在打字稿构造函数之外正确使用角度 $timeout 服务?
【发布时间】:2015-04-12 21:34:29
【问题描述】:

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

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

- 没有任何成功...

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

如果有人能告诉我如何正确使用 $timeout 和其他类似的服务,我将不胜感激 - 最好使用我的目标样式指南,即使用“controllerAs with vm” - John Papa

【问题讨论】:

  • 你可能会觉得这个视频很有启发性:youtube.com/watch?v=tvocUcbCupA
  • @basarat - 谢谢,我确实觉得它很有启发性。以前看过你的几个视频(不幸的是不是你指给我的那个),我希望你能继续制作更多! :)

标签: angularjs typescript


【解决方案1】:
this.$timeout(()=> {
                this.ready = true;
            }, 2200);

如果您使用 function(){} 模式,您将无法访问 thisthis 不是您所期望的)

【讨论】:

  • 太棒了!好东西。我应该记得至少在我的构造函数之外的方法中使用这个 lambda 语法。谢谢!
【解决方案2】:

timeout里面的'this'就是timeout函数的this。您需要在外部定义一个变量来引用该范围(通常称为“that”)并在超时内引用它:

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

【讨论】:

  • 请不要在使用TypeScript时记住thisTypeScript 是关于 this 的“魔法”!
【解决方案3】:

试试这个,伙计

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

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2023-03-29
    • 2018-02-20
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多