Home > Mobile >  How to make the Angular compiler wait the subscription before return
How to make the Angular compiler wait the subscription before return

Time:10-06

I have a function has to return a value and inside it I have a subscription, my problem is the return line is being executed before the subscription end,

testFunc(){
let objectType;
          let moduleId;
          objectType = valueAsString.split('|');
          objectType = objectType[0];
          this.layoutService.moduleIdByType(objectType)
            .toPromise().then(data => {
              moduleId = data;
            });
          return { IsById: true, LinkedModule: moduleId };
}

here I have (moduleIdbytype) and it is changing the value of moduleId variable and I have to return after the subscription finished and changed the var's value

CodePudding user response:

You can make your testFunc() async and await the subscription.

async testFunc(){
 let objectType;
 let moduleId;
 objectType = valueAsString.split('|');
 objectType = objectType[0];
 const moduleId  = await this.layoutService.moduleIdByType(objectType)
 .toPromise();
 return { IsById: true, LinkedModule: moduleId };
}
  • Related