简体   繁体   English

如何让Angular编译器在返回前等待订阅

[英]How to make the Angular compiler wait the subscription before return

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,我有一个 function 必须返回一个值并且在其中我有一个订阅,我的问题是返回行在订阅结束之前被执行,

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这里我有 (moduleIdbytype) 并且它正在更改 moduleId 变量的值,我必须在订阅完成后返回并更改 var 的值

You can make your testFunc() async and await the subscription.您可以使 testFunc() 异步并等待订阅。

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 };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM