I am fairly new to Angular trying to understand a codebase that was written by a 3rd party. We're trying to fetch a simple json object from an API that returns data in this shape.
{
"total": 18,
"completed_items": 18
}
We are trying to fetch this from a home compontent that looks like this:
console.log('in init'); // this executes
this.requiredByYouOverview$ = this.requiredService
.getRequiredOverview()
.pipe(
tap((requiredOverview: RequiredOverview) => {
console.log('in tap'); // this occasionally executes
this.allRequiredItemsCompleted =
requiredOverview.total > 0 &&
requiredOverview.total === requiredOverview.completedItems;
})
);
The required service looks like this:
export class RequiredService {
...
public getRequiredOverview(): Observable<RequiredOverview> {
console.log('in getRequiredOverview'); // this executes
return this.http
.get<RequiredOverviewRaw>(
`${this.apiService.getApiEndpoint()}${
environment.requiredOverviewApiEndpoint
}`
)
.pipe(
map((reqOverviewRaw: RequiredOverviewRaw) =>
RequiredMapper.mapOverviewFromRaw(reqOverviewRaw)
)
);
}
and the required mapper looks like this:
export class RequiredMapper {
public static mapOverviewFromRaw(
reqOverviewRaw: RequiredOverviewRaw
): RequiredOverview {
console.log('in mapOverviewFromRaw'); // this occasionally executes
const reqOverview: RequiredOverview = {
total: reqOverviewRaw.total,
completedItems: reqOverviewRaw.completed_items,
};
return reqOverview;
}
}
The console will sometimes show:
in init home.component.ts:151:12
in getRequiredOverview required.service.ts:33:12
but will just as often show:
in init home.component.ts:151:12
in getRequiredOverview required.service.ts:33:12
in mapOverviewFromRaw required.mapper.ts:8:12
in tap home.component.ts:156:18
How can I get this to work consistently?
CodePudding user response:
it's hard to say... but in init
and in getRequiredOverview
are called immediately, this is expected.
in mapOverviewFromRaw
is only called after the first HTTP request has completed and in tap
will be only called after afterwards this is also expected.
So maybe the HTTP request is really slow (network or server problem) or there is an error and therefore the request stops and fails and you won't see the logs.
CodePudding user response:
So my fix for this has been to turn the compontents pipe / tap into a subscribe.
this.requiredService
.getRequiredOverview()
.subscribe((requiredOverview: RequiredOverview) => {
this.allRequiredItemsCompleted =
requiredOverview.total > 0 &&
requiredOverview.total === requiredOverview.completedItems;
});
I am unsure if this is an optimal solution but it seems to work for me.