为什么在使用promise构造时angularjs抛出“非法调用”?

时间:2019-04-04 13:20:45

标签: angularjs promise location

我调用一些promise函数:

return $http.post("anyCtrl").then(location.reload);

之后,我在浏览器控制台“ Illegal invocation”中以angular抛出异常。

如果我调用:

return $http.post("anyCtrl").then(function(){location.reload()});

一切都很好。

我希望我所有的代码段都可以正常工作。

1 个答案:

答案 0 :(得分:0)

location.reload作为参数传递与重新分配参数大致相同。如果您重新分配对象的方法且未绑定该方法,则该对象的this将成为为其分配的对象。例如:

const notlocation = {};
notlocation.reload = location.reload();
notlocation.reload(); // illegal invocation

您需要从reload对象调用location。您可以通过两种方法来执行此操作。一种是在完成后显式地将带有方法调用的括号括起来:

$http.post("anyCtrl").then(() => location.reload());

另一种方法是使用.bind并将其绑定到您要调用该方法的对象:

$http.post("anyCtrl").then(location.reload.bind(location));