Angularjs 如何访问链接的$request承诺中的$scope?
我有一个像这样的承诺链Angularjs 如何访问链接的$request承诺中的$scope?,angularjs,promise,angularjs-resource,Angularjs,Promise,Angularjs Resource,我有一个像这样的承诺链 this.getFile(fileId).then(updateFile).then(displayAllDoneMessage); 其中getFile()和updateFile()分别使用ngResource构造适当的JSON调用,然后返回$resource.$promise 链启动正常,但从updateFile 所以在getFile()中 // this works this.status.text = "fetching file" // this fails
this.getFile(fileId).then(updateFile).then(displayAllDoneMessage);
其中getFile()
和updateFile()
分别使用ngResource
构造适当的JSON调用,然后返回$resource.$promise
链启动正常,但从updateFile
所以在getFile()
中
// this works
this.status.text = "fetching file"
// this fails at runtime because "this" is not $scope
this.status.text = "updating file"
但是在updateFile()
中,我有
// this works
this.status.text = "fetching file"
// this fails at runtime because "this" is not $scope
this.status.text = "updating file"
我做错了什么,或者我还需要做什么才能使updateFile()中的$scope
可用
我可能应该补充一点,我使用的是TypeScript,以防它有意义。当您调用this.getFile
时,上下文是this
,在您的情况下,我猜this
是$scope对象,因此getFile
中的是$scope
但是,updateFile
和displayAllDoneMessage
被框架作为回调调用,此
不再引用$scope
尝试将$scope绑定为上下文:
this.getFile(fileId).then(updateFile.bind(this)).then(displayAllDoneMessage.bind(this));
对于较旧的浏览器,可以将此脚本作为polyfill(引用自文档):
如果您使用的是TypeScript,并且希望维护此
指针,那么您需要确保使用的是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使用闭包来维护对此的适当引用。您是否使用“controller as”语法?我没有,但这是我下一步要尝试的内容之一。感谢您的解释和建议的解决方案,并链接到bind()。当我阅读Mozilla文档时,它表明bind仅在IE9及以上版本上受支持。这是否会使此解决方案不适用于较旧的浏览器?@pinoyyid:有一个polyfill实现。您可以包含该脚本以使其与较旧的浏览器配合使用。感谢您花费额外的时间添加polyfill。回答得很好。我已经测试了这个,并确认它是有效的。这也将有助于解决代码中的范围问题,因此doubleplusgood。向上投票!我接受了@KhanhTO的答案,只是因为从语法上讲它更干净,这是我使用承诺代替嵌套回调的目标之一。