javascript - Return a promised value to variable in angular.extend() -
in example below, how can set myvar value return async service method
angular.extend(this, { myvar: (function() { getval(); })() }); function getval() { var d = $q.defer(); myfactory.get() .then(function (resp) { d.resolve(resp.data); }); return d.promise; // myvar should equal resp.data };
i think i'm showing lack of understanding of promises/deferral, advice great.
since myvar variable set anywhere in controller. in initialization can assign fallback value or set undefined. , set after async call success.
angular.extend(vm, { myvar: 'fallback' });
or:
angular.extend(vm, { });
then: in controller:
getvar(); function getvar() { getval().then(function(data){ vm.myvar = data; }); } function getval() { var d = $q.defer(); myfactory.get() .then(function (resp) { d.resolve(resp.data); }); return d.promise; // myvar should equal resp.data };
or more efficiently:
getval(); function getval() { myfactory.get() .then(function (resp) { vm.myvar = resp.data; }); };
changed this
vm
removing conflict this
keyword may throw.
Comments
Post a Comment