简体   繁体   中英

Angular : How to handle the async set of a variable

Under my Angular 6 app , i have this service ; where i'm declaring a varibale called permittedPefs , this variable is setted asychronsouly within a httpClient.get call.

@Injectable()
    export class myService implements OnInit {

      permittedPefs = [];
      constructor(){}

      ngOnInit() {
      // STEP 1
      this.loadUserPefsService.getUserRolePefs(roleId).subscribe(
          (returnedListPefs) => {
            this.permittedPefs = returnedListPefs;
          },
          error => {
            console.log(error);
          });
      }
      // STEP 2
      this.myMethod(1);

After that , i ve a call of this method which is using my -supposed setted - var

myMethod(pefId): boolean {
        return this.permittedPefs.includes(pefId);
}

the problem is it seems that permittedPefs , haven't got its value yet , and the call of myMethod() point to a wrong value of " permittedPefs "

So what's the simpliest way to make it wait to the just after the http response , without calling if from the http Response callback (as i 'm using it in several places)

Sugesstions??

Call the method this.myMethod(1); from subscription block, so that you wait for asynchronous call to be completed, which will then set the value of permittedPefs .

ngOnInit() {
      // STEP 1
      this.loadUserPefsService.getUserRolePefs(roleId).subscribe(
          (returnedListPefs) => {
            this.permittedPefs = returnedListPefs;
           // STEP 2
           this.myMethod(1);  // check this line
          },
          error => {
            console.log(error);
          });
}

Asynchronous Hell ! the best choice here is to get an Observable instead of a value

in your service :

getValue (): Observable<any>{

return this.loadUserPefsService.getUserRolePefs(roleId);

}

in your method :

 myMethod(pefId): boolean {

       this.yourservice.getValue().subscribe(
       data => {

         if(data){
            return data.includes(pefId);
             }

        });

}

This happens because your method is called when you have not received the result yet. so just move the function call in subscribe function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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