我在像这样的 Angular 应用程序中有一个 $http promise :
this.data = $http.get('/api/foo', {})
然后,我的应用程序的其他部分将成功和错误处理程序添加到此 promise 中。
我的问题是我想刷新 this.data
变量中的信息,然后重新运行所有 promise 的附加处理程序。这可以通过某种 this.data.$refresh()
方法来完成,还是我必须将所有处理程序存储在其他地方并将它们重新附加到新的 $http.get?
编辑:也许一个更清晰的例子:
this.data = $http.get('/api/foo', {})
this.data.success(doSomething)
// doSomething() runs because the response arrives.
this.data.someMagic()
// doSomething() runs again without being reattached.
我想避免的是:
this.data = $http.get('/api/foo', {})
this.data.success(doSomething)
// Time passes...
this.data = $http.get('/api/foo', {}) // All old handlers have now been thrown away.
this.data.success(doSomething)
这是因为成功和错误都有多个处理程序,并且它们是由不同的 Controller 和服务添加的,因此需要一些困惑的回调系统来让它们在每次更新变量时重新附加其处理程序。
最佳答案
re-run all the promise's attached handlers.
不,那是不可能的。根据契约(Contract), promise 仅解析并执行其处理程序一次。
would I have to store all the handlers somewhere else and reattach them to a new $http.get?
是的,这是一个可能的解决方案,尽管它失去了 promise 的所有良好属性,例如可链接性。您不妨简单地放置一个 EventEmitter 并实现某种发布-订阅(例如,请参阅 Angularjs pubsub vs $broadcast)。
如果您想拥有一个包含各种好东西的真正的流接口(interface),您可能需要查看 FRP ,例如与 Bacon.js和 angular-bacon .
关于javascript - "Resend"一个 Angular $http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25744202/