Having recently started working with Angular and TypeScript, my question may seem a bit off. I'm currently using Visual Studio Code along with Angular 5 (ng-version="5.2.11").
I am faced with the challenge of waiting for my API call to finish and return its result without having to wrap everything in a huge ".subscribe" block. Here is what I have:
exampleMethod(): SettingsClass {
const myComplexObject: SettingsClass = {
field1: predefined.field1,
field2: predefined.field2,
field3: isComplexCalculationsNecessary ? this.CallApi_1(predefined.paramForField3) : predefined.field3,
};
return myComplexObject;
}
Previously, all parameters were in "predefined", but now I need to fetch one(or more) from an external source and immediately return "myComplexObject" from the method without delay. How can I write the API call to avoid rewriting my code every time I need to add a new external call? Something like:
CallApi_1(paramForField3: string): Observable<int> {
return this.http.get(`${httpConfig.route}?$apply=filter${paramForField3}/groupby${httpConfig.groupingParam}`);
}
OR maybe
CallApi_1(paramForField3: string): Observable<int> {
return this.ExternalCallsService.GetParam3Information(paramForField3).subscribe(res =>
.GetParam3Information contains the same http call as above, but I need to do
something to return this result outside, I don't know what);
}
What I'm looking for is something like:
field3: isComplexCalculationsNecessary ? **await** this.CallApi(predefined.paramForField3) : predefined.field3,
Currently I am experimenting with 'rxjs' which offers interesting options for working with Observables, such as 'forkJoin', but I am not sure if I am on the right track. Maybe this kind of trick is not possible, or perhaps my understanding of Observables is incorrect and I should move complex logic to the back-end instead? Please advise.
It's important to emphasize once again that a simple ".subscribe" is not what I'm after because in all subscribe examples, values are not returned but assigned to global variables or directly to HTML elements, which is NOT what I require. I need to retrieve the value and continue working with it as soon as the external resource returns it.