I need to implement a "loading" variable for my login method:
Here is the current login method:
public login(authDetails:any):any{
return this.http.post<any>('https://myapi.com/session', authDetails).pipe(
map(response => {
this.sessionStore.update(response.data.attributes)
}
)
)
}
The loading variable can be set using
this.sessionStore.setLoading(true/false)
.
While it's clear where to call setLoading(false)
, I am unsure about where to put setLoading(true)
since the subscribe method will be called externally.
Identifying when loading should be turned off is straightforward
(Update: it's not: see the comments below. In summary, the .setLoading(false)
call should happen in a .finalize
method to ensure it also happens during errors)
public login(authDetails:any):any{
return this.http.post<any>('https://myapi.com/session', authDetails).pipe(
map(response => {
this.sessionStore.update(response.data.attributes)
// setLoading to false here:
this.sessionStore.setLoading(false); // <= Loading ended
}
)
)
}
Where should loading be switched on?
.setLoading(true)
needs to be triggered when the observable is subscribed to. I want to maintain the loading behavior within this function for reusability, but I'm uncertain how to sync calling setLoading(true)
with the subscription to the observable.
In the past, an onSubscribe
event might have been used, but I suspect that's not the RxJS way.
Do you need to wait for .subscribe() or is it implicit?
Should I simply place it at the beginning of the method? I hesitate because it's not explicitly clear if the code has been subscribed to at that point.
public login(authDetails:any):any{
this.sessionStore.setLoading(true); // <= Correct?!
return this.http.post<any>('https://myapi.com/session', authDetails).pipe(
map(response => {
this.sessionStore.update(response.data.attributes)
this.sessionStore.setLoading(false); // <= Loading ended
}
)
)
}