javascript - callback issue in angularjs directive -


i facing call problem when calling service function

here function defined in registrationservice

function hasuseraccesstolevel(incentivelevel, callback, showregistrationview) {              var url = "...";             httpwrapperservice.get(url)                 .then(                 function success(data) {                     var hasaccess = incentivelevel <= data.level;                     callback(hasaccess);                     if (showregistrationview && hasaccess == false) {                         showregistrationviewforlevel(incentivelevel);                     }                 },                 function error(errorobject) {                      alert("user has not access\r\ntodo : show popup registration/login");                 }              );             return false;         } 

and in directive using function

function checkauthentication() {                 registrationservice.hasuseraccesstolevel(2, function (hasaccess) {                     if (hasaccess == false){                         return false;                     }                     else{                         return true;                     }                 });             }     function loaddocuments() {                 var target=checkauthentication()                 if(target)                 {                   //load both private , public                 }                 else                 {                   // load public                 }              } 

now problem facing , have function loadocuments , when user logged in should come inside if(target) block, when debuggin function saying target undefined , hence control going else part , wrong. know there callback issue dont know how rectify it.

any appriciable. thanks

you shall use $q service. checkauthentication() return undefined because hasuseraccesstolevel() asynchronys , @ time of call hasn't return value. solution return promise object.

you code can written this:

function checkauthentication() {     var defer = $q.defer();     registrationservice.hasuseraccesstolevel(2, function (hasaccess) {         defer.resolve(hasaccess);     }, function () {         defer.reject();     });     return defer.promise; }  function loaddocuments() {     checkauthentication().then(function (target) {         if (target) {             //load both private , public         }         else {            // load public         }     }); } 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -