I have been tasked with exploring how to make a service call and return the final result instead of an observable. Within the service, there is a method structured like this:
getToken(name: string, pass: string): string {
const url = "https://localhost:44310/api/Security/login";
const data = { name, pass };
return this.http.post<any>(url, data);
}
In the component where it will be used, we typically subscribe to it and handle the result that comes back (or handle any errors that occur). Now, I am looking to implement a private field that will be checked when calling getToken(...) and returned if it has already been assigned. If not, then I want to make a POST request, store the result, and then return it.
private token: string;
getToken(name: string, pass: string): string {
if(this.token)
return this.token;
const url = "https://localhost:44310/api/Security/login";
const data = { name, pass };
this.http.post<any>(url, data)
.subscribe(
suc => this.token = suc,
err => this.token = null);
return this.token;
}
However, this approach will fail because the asynchronously assigned value to this.token may not be available by the time the method finishes. Trying to return the token within the success callback like this:
this.http.post<any>(url, data)
.subscribe(
suc => { this.token = suc; return this.token; },
err => this.token = null);
is unlikely to work any better. I am currently stuck and starting to think that there may not be a way to return a definitive value without using the subscription in the component.
Is there a way to implement the described field as intended?
I have attempted to follow this post but it resulted in an error: Property 'map' does not exist on type 'Observable'.