Struggling to grasp the concept of waiting for an observable to complete while learning Angular (Typescript) + ASP Net Core. I've set up a login service on the backend that's functioning correctly. However, I encountered an issue when trying to create a simple helper to streamline handling http responses on the client side. The problem arises as it runs twice: initially, it assumes RequestResponse is undefined (due to skipping the http request), but on the second run, RequestResponse is populated and works as intended.
Take a look at the Http helper below:
get<T>(url: string): Observable<T> {
let options = this.doHeaders();
return this.doSub(this.http.get(this.doUrl(url), options));
}
private doSub<T>(obs: Observable<Response>) {
var ob1: Observable<T> = obs.map(this.extractData)
.catch(this.handleError);
return ob1;
}
And here's the definition of RequestResponse:
export class RequestResponse {
public error: string;
public isOk: boolean;
public code : StatusCode;
}
Additionally, there's the Service implementation:
@(Injectable)
export class RequestService {
constructor(
private net: NetworkService,
private loaderService: LoaderService,
private storage: StorageService,
) {
}
login(email: string, password: string, rememberMe: boolean = false): RequestResponse {
var r = new RequestResponse();
// Need to figure out how to make this wait
this.net.get<LoginModel>(`Authentication/Login/${email}/${password}`).subscribe(t => {
this.storage.token = t.token;
this.storage.email = rememberMe ? email : null;
this.storage.password = rememberMe ? password : null;
r.isOk = true;
r.code = StatusCode.OK;
},
error => {
r.isOk = false;
switch (error.message) {
case '403':
r.code = StatusCode.Forbidden; r.error = 'You've been suspended'; return;
case '404':
r.code = StatusCode.NotFound; r.error = 'User not found'; return;
case '406':
r.code = StatusCode.NotAcceptable; r.error = 'Invalid Email/Password'; return;
default:
r.code = StatusCode.InternalServerError; r.error = 'Internal Error'; return;
}
});
return r; // Issue with first response being null
}
}
This is how I'm attempting to use it:
login() {
this.loginResponse = this.requestService.login(this.email, this.password, this.rememberMe);
console.log(this.loginResponse);
if (!this.loginResponse.isOk) {
this.toasterService.pop('error', 'Error', this.loginResponse.error);
return;
}
this.router.navigateByUrl('/home');
}
Despite exploring Promises and Observables and making several adjustments, the initial RequestResponse being null continues to be a concern. Any suggestions on how to tackle this challenge?