简体   繁体   中英

“Resend” an Angular $http request

I have an $http promise in an angular app like this:

this.data = $http.get('/api/foo', {})

Other parts of my app then add success and error handlers to this promise.

My problem is that I want to refresh the information within the this.data variable and then re-run all the promise's attached handlers. Can this be done with some sort of this.data.$refresh() method, or would I have to store all the handlers somewhere else and reattach them to a new $http.get?


EDIT: Maybe a slightly clearer example:

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.

What I want to avoid is this:

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)

This is because there are several handlers on both success and error, and they are added by different controllers and services, so it would require some messy callback system to get them all to reattach their handlers every time the variable was updated.

re-run all the promise's attached handlers.

No, that's impossible. By contract, a promise resolves and executes its handlers only once.

would I have to store all the handlers somewhere else and reattach them to a new $http.get?

Yes, that's a possible solution, although it looses all the nice properties of promises like chainability. You might as well simply put an EventEmitter and implement some kind of pub-sub (see Angularjs pubsub vs $broadcast for example).

If you want to have a real stream interface with all kinds of goodies, you may want to look into FRP , eg with Bacon.js and angular-bacon .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM