【问题标题】:Why angularjs throw 'Illegal invocation' when using promise construction?为什么angularjs在使用promise构造时会抛出“非法调用”?
【发布时间】:2019-04-04 21:24:46
【问题描述】:
我调用了一些 promise 函数:
return $http.post("anyCtrl").then(location.reload);
之后,我在浏览器控制台“非法调用”中以 Angular 抛出异常。
如果我调用:
return $http.post("anyCtrl").then(function(){location.reload()});
一切都很好。
我希望我的所有代码 sn-ps 都应该可以工作。
【问题讨论】:
标签:
angularjs
promise
location
【解决方案1】:
将location.reload 作为参数传递或多或少与重新分配它相同。如果您重新分配一个对象的方法并且它没有被绑定,那么该对象的this 将成为它被分配给的对象。例如:
const notlocation = {};
notlocation.reload = location.reload();
notlocation.reload(); // illegal invocation
您需要从location 对象调用reload。有几种方法可以做到这一点。一种是像您所做的那样显式地在方法调用中加上括号:
$http.post("anyCtrl").then(() => location.reload());
另一种是使用.bind并将其绑定到要调用该方法的对象:
$http.post("anyCtrl").then(location.reload.bind(location));