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
Post a Comment