vendredi 10 avril 2020

Getting ready a service in Angular before to be used

I'm pretty new in Angular. I don't know if this pattern that I'm using in various services is correct. My service needs do some http requests in order to be ready. The constructors can't be async so I solve this problem in this way:

Service

export class MyService {

    constructor(HttpClient:http) {
    }

    private  longAndNeededMethod():Observable{
       //Blablabla....
       return http.post(...);
    }

    async ready() {
      if(notReady){
        await longAndNeedMethod().toPromise().then(
          (response)=>{
               //do something
          });
      }
    }

    //Another methods
}

Component

export class MyComponent{
  constructor(private myService:MyService){}

  async onInit(){
    await myService.ready();
  }

  //Another methods
}

Is this design correct?

Thanks

Aucun commentaire:

Enregistrer un commentaire