In my current code, there is a function that handles login functionality:
/**
* Login with provided username and password
* @returns {Observable<number>} the status code of the HTTP response
*/
login(username: string, password: string): Observable<number> {
let body = new URLSearchParams();
body.append('grant_type', 'password');
body.append('username', username);
body.append('password', password);
return this.http.post(Constants.LOGIN_URL, body, null)
.do(res => {
if (res.status == 200) {
this.authTokenService.setAuthToken(res.json().auth_token);
}
})
.map(res => res.status)
.catch(err => { return Observable.throw(err.status) });
}
The purpose of this function is to attempt a login operation and provide an Observable<number>
as feedback regarding the HTTP response status code.
However, I noticed a flaw in the implementation. If the caller of this function does not subscribe to the returned Observable
, the do
function is not executed, resulting in the failure to save the received auth token.
Upon reviewing the documentation for do
, it is explained that this method acts as an observer without triggering any execution unless subscribed to:
Note: this is different from subscribing to the Observable. do only observes existing execution, without triggering it like subscribe does.
To ensure that the side effect of saving the auth token occurs regardless of whether the caller subscribes or not, what steps should be taken?