【问题标题】:How do I access $scope in chained $request promises?如何在链式 $request 承诺中访问 $scope?
【发布时间】:2014-05-18 05:34:48
【问题描述】:

我有一个看起来像这样的承诺链......

this.getFile(fileId).then(updateFile).then(displayAllDoneMessage);

其中getFile() 和updateFile() 分别使用ngResource 构造相应的JSON 调用,然后返回$resource.$promise。

链触发正常,但我在从 updateFile 中访问 $scope 时遇到问题

所以在getFile()我有

// this works
this.status.text = "fetching file"

但是在updateFile()我有

// this fails at runtime because "this" is not $scope
this.status.text = "updating file"

我做错了什么,或者我需要做些什么才能使$scope 在updateFile() 中可用?

我可能应该补充一点,我正在使用 TypeScript,以防万一。

【问题讨论】:

  • 你使用的是“controller as”语法吗?
  • 我不是,但这是我接下来要尝试的事情之一。

标签: angularjs promise angularjs-resource


【解决方案1】:

如果您使用的是 TypeScript 并且想要维护您的 this 指针,那么您需要确保您使用的是 lambda 语法。

假设您已将 $scope 保存为构造函数中的私有/公共变量,如下所示:

constructor(private $scope){ /* snip */ }

然后您可以简单地执行此操作以确保您可以像这样访问您的$scope:

this.getFile(fileid)
.then((result) => {
   return this.$scope.updateFile(result);
})
.then((result) => {
   return this.$scope.displayAllDoneMessage(result);
});

在后台,它会被编译成如下内容:

//Save 'this' off to a closure
var _this = this;

_this.getFile(fileid)
.then(function(result){
   return _this.$scope.updateFile(result);
})
.then(function(result){
   return _this.$scope.displayAllDoneMessage(result);
});

TypeScipt 使用闭包来维护对this 的适当引用

【讨论】:

  • 很好的答案。我已经对此进行了测试并确认它有效。这也将有助于解决我的代码中的范围问题,所以 doubleplusgood。点赞!我接受了@KhanhTO 的答案,仅仅是因为它在语法上更简洁,这是我使用 Promise 代替嵌套回调的目标之一。
【解决方案2】:

当你调用this.getFile 时,上下文是this,在你的情况下,我猜this 是$scope 对象,所以getFile 中的this 是$scope。

但是updateFile 和displayAllDoneMessage 被框架作为回调调用,this 不再引用$scope。

尝试.bind将$scope绑定为上下文:

this.getFile(fileId).then(updateFile.bind(this)).then(displayAllDoneMessage.bind(this));

对于较旧的浏览器,您可以将此脚本作为 polyfill 包含(引用自文档):

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

【讨论】:

  • 感谢您的解释和建议的解决方案,并链接到 bind()。当我阅读 Mozilla 文档时,它表明绑定仅在 IE9 及更高版本上受支持。这会使这个解决方案不适合旧版浏览器吗?
  • @pinoyyid:有一个作为 polyfill 的实现。您可以包含该脚本以使其适用于旧版浏览器。
  • 感谢您抽出额外的时间来添加 polyfill。
猜你喜欢
  • 2013-12-08
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-13
相关资源
最近更新 更多