I'd like to set a "loading" variable for a login method:
The 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)
}
)
)
}
tho loading variable can easily be set via this.sessionStore.setLoading(true/false)
.
It's clear where I can call setLoading(false)
but since the .subscribe
method is going to be called externally, I don't know where where to put setLoading(true)
.
The place where loading is switched off is clear
(Update: it's not: see the comments below but in short the .setLoading(false)
call should happen in a .finalize
method so that it happens even when there are 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)
// I can be confident that the HTTP response has
// concluded and setLoading to false here:
this.sessionStore.setLoading(false); // <= Loading ended
}
)
)
}
Where is loading switched on?
.setLoading(true)
needs to be called when the observable is subscribed to. I'd like to keep the loading behaviour contained within this function so that it's reused along with the function itself but it's not clear to me how I would call setLoading(true)
in sync with the observable having been subscribed to.
In the old pre-observable world there would have probably been an onSubscribe
event that I could have used but I've a feeling that's not how things are done in RxJS.
Do you even need to wait for .subscribe() or is it implicit?
Is it just as simple as putting it immediately at the top of the method? I'm hesitant just because it's not explicitly clear to me that it has been subscribed at the point that that code is parsed.
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
}
)
)
}