angularjs - How to wrap a resource which depends on async call -


i have service wraps resource. have had refactor take param (websiteid) gotten async call. thought wrap resource inside resource, getting standard injection error.

what correct way have service wraps resource, use param comes promise?

searchapp.factory('mytestservice', ['$resource', 'websiteservice', 'appconfig',  function ($resource, websiteservice, appconfig) {   websiteservice.getcurrentwebsiteid().then(function(websiteid){      return $resource(appconfig.apibaseurl + 'tests/:id/?website=:websiteid', {         websiteid: websiteid     });   }); }]); 

i try approach:

searchapp.factory( 'mytestservice', [ '$resource', 'websiteservice', 'appconfig', '$q'  function ( $resource, websiteservice, appconfig, $q ) {   var getservice = function() {     var defer = $q.defer();     websiteservice.getcurrentwebsiteid( function( websiteid ) {       defer.resolve({          websiteid : websiteid,          resource : $resource( appconfig.apibaseurl + 'tests/:id/?website=:websiteid', {           websiteid: '@websiteid'         })       });     });     return defer.promise;   };   return getservice; }]); 

main differences are:

  • returning promise service.
  • parameter value prefixed @ -> value parameter extracted corresponding property on data object (provided when calling action method). example, if defaultparam object {someparam: '@someprop'} value of someparam data.someprop.

edit

how use it

since service returning promise value resource object, use first have resolve service promise , call appropiate resource class object (im using same terminology angular documentation). once have resource class object, can request resource , resolve it.

the correct usage be:

mytestservice.then( function( responseobject ) {   responseobject.resource.get( { websiteid : responseobject.websiteid }, function( response ) {     console.log( response );   }) }); 

another different history why need this. if you, create different resources , nest promises, in order resolve 1 before getting other.

but thats not question.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -