angularjs - Two controllers depending on same data returned asynchronously -


there app allows users create or join rooms. there roomslistcontroller displays rooms, roomdetailscontroller shows contents , controls activity inside particular room. , of cause, roomservice provides getrooms() (async) method.

now angular way make 2 controllers wait same data returned roomservice.getrooms()?

details:

  • there authentication in app , list of rooms depend on userid. calling roomservice.getrooms() @ application start not option
  • roomdetailscontroller doesn't request list of rooms. whenever room provided via $stateparams exists , active displayed. if not, there logic guides user room (here list of rooms required) or displays message no rooms available , perhaps it's time create one.
  • let's assume getrooms() heavy operation server , it's not desired twice when same data on client can reused.
  • it's desired have logic doesn't depend 1 controller function executed first, can influenced layout update in template

take @ route resolve promises.

you'll call async method before route resolves:

// in config $routeprovider.when('/your-route', {   resolve: {     roomdata: function(roomservice) {       return roomservice.getrooms();     }   } }  // roomslistcontroller function(roomdata) {   // roomdata }  // roomdetailscontroller function(roomdata) {   // roomdata } 

this way, far controllers concerned, data there before route loads.

you've touched on 1 of key issues applications... is, creating single source of truth data composed in way application can consume it.

there many patterns solving this, i'd recommend taking @ route resolution promises starting point, , branching out there. can become complex.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -