Issue
I'm writing an Angular service that will return a number value from a REST endpoint. The endpoint call works fine and data comes back properly but my service function is exiting before assigning the endpoint return value to my variable from what I see while debugging...
I'm using Angular 14.0.0 and RxJS 7.5.0.
Here is my code:
In my-service.ts:
public getCurrentWeek(selectedPoolSeason: PoolSeason | undefined) : number {
let currentWeek : number | undefined;
let seasonId : number | undefined = selectedPoolSeason?.seasonId;
this.client?.currentWeek(seasonId!, "1", selectedPoolSeason?.tournamentId?.toString()!).subscribe(data => {
currentWeek = data;
});
return currentWeek!;
Calling the function from my-component.ts:
this.currentWeek = this.weekPickerService.getCurrentWeek(this.selectedPoolSeason);
In the above line, this.currentWeek
comes as undefined after calling the function.
What am I doing wrong? most examples I see online assign the REST call response to a local class-level variable instead of returning the value directly. Any suggestions?
Solution
You're thinking async
calls work like synchronous
calls. Inside getCurrentWeek
call you're having a subscription
. and returning the currentWeek
value right after that. So when ajax triggered it do not wait for subscribe function get called, it just move ahead to next line and return currentWeek
value.
To fix this error I would suggest you to return Observable
stream from getCurrentWeek
function and move .subscribe
to component.
public getCurrentWeek(selectedPoolSeason: PoolSeason | undefined) : Observable<number> {
let seasonId : number | undefined = selectedPoolSeason?.seasonId;
return this.client?.currentWeek(seasonId!, "1", selectedPoolSeason?.tournamentId?.toString()!)
});
};
In component either you can use subscription to retrieve a value
this.weekPickerService.getCurrentWeek(this.selectedPoolSeason).subscribe((currentWeek) => {
this.currentWeek = currentWeek;
});
OR
Using async
pipe (recommended)
// need to change currentWeek type in this case
currentWeek = Observable<number>
this.currentWeek = this.weekPickerService.getCurrentWeek(this.selectedPoolSeason)
HTML
{{ currentWeek | async }}
Answered By - Pankaj Parkar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.