I need to reuse a function across components that makes a call to multiple services. So my idea was to create a service which in turn calls the other services.
Component
this.resul = this.escribirService.escribir(param1,param2);
console.log(this.resul);
this is the service
public escribir(
param1: number,
param2: string,
): boolean {
let resultadoFinal:boolean = false;
this.subscriptions.push(
this.servicioL
.getinfo1(param1, param2
)
.subscribe((resul1) => {
resultadoFinal = resul1;
}),
this.servicioL
.getinfo2(param1, param2
)
.subscribe((resul2) => {
resultadoFinal = resul2;
}),
return resultadoFinal;
}
Clearly the return is incorrect and it always returns false since the return of the subscriptions arrive later. The question is, am I making a mistake creating a service to reuse this function? If it is correct to do this service, how do I make it synchronous and return the results of the subscriptions to the component? Thank you
The truth is that to do what you want, you must use await and async for the synchronous handling you want, but you have to take several things into account, since when doing this, in Angular the function you have returning the type
boolean
, already it's not going to be like that. but would return aPromise<boolean>
In the same way I will leave you the example of how you should do it.
Since as I mentioned, In the function
escribir
, the return will no longer be aboolean
but aPromise<boolean>
, this would be the way you should get the information that the service returns to you.Another option on how to obtain the information in your component is that you do the same thing to the function that you have in your Component, where you call the write function of your services, that we did in the Service.
I recommend this last option if the function where you call the write service in your Component is not going to make any return.
You can use the async and await handling on the following page https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Statements/async_function
I hope it helps you.