简体   繁体   中英

angularjs async http post update scope data

I am building chat module using angularjs.

I built an algorithm which creates a new chat, this is what it does:

  1. click on new chat button
  2. show list of avaliable people to chat with
  3. choose one person (click), then call function createChat
  4. create chat creates new chat object locally (in the js code) and takes you to chat page
  5. when you submit a new message, if chat_id = 0, it creates new chat in the database with a $http post request, and in the success I set chat_id to whatever chat_id returned from the http post request.

my problem is that in angular, requests are async, so setting chat_id inside the success function does not update it outside of the success function, and then when I send next message chat_id is still 0..

I tried reading about angularjs $q, but couldn't understand how it helps.

$q is just a promise library, which means it makes writing async code a little easier and a little more readable. Promises essentially are placeholders for the eventual result of an async call. They allow you to chain functions that act on that eventual result, but only get invoked once you have it. They're just an abstraction on top of async code—they won't necessarily help solve your problem. See MDN's description of promises for more info.

You say "requests are async, so setting chat_id inside the success function does not update it outside of the success function," but that problem has nothing to do with async code. Are you sure the success function is actually running, and you aren't getting any errors? If that is the case, it's probably just an issue of proper scoping. Do you mind posting some relevant code?

You have two possibilities: 1. Freeze (ie show waiting icon) chat after first message untill u receive response with chat_id. 2. Before first message is sent, generate some unique string - all messages will have this string as a chat id until real chat id arrives. Handle this on the server side.

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