How can I save this response to a variable so that I can access it from other functions?
Code:
export interface launchResponse {
status: number;
url: string;
token: string;
}
export interface launchResponseObject {
response: launchResponse;
}
Then in a service:
LAUNCHRESPONSE: launchResponseObject[] = [];
async getData() {
try {
const LAUNCHRESPONSE = await this.http
.get<launchResponseObject>(
`${$apiUrl}`
)
.toPromise();
console.log(LAUNCHRESPONSE.response.url)
console.log(LAUNCHRESPONSE.response.token)
} catch (error) {
console.log(`Promise rejected with ${JSON.stringify(error)}`);
}
}
I know I can save it like this: this.url = LAUNCHRESPONSE.response.url but I want to save the whole thing and then access it like I do in this function in other functions aswell.
I've also tried using this.LAUNCHRESPONSE instead of the const LAUNCHRESPONSE with no luck..I know it's something really stupid but I can't find out what.
Not sure what you mean by saving the whole thing and access like the function you have written. If your requirement is to get the value you got from api response without calling it again, you can use a getter function for it after setting the api response using this.LAUNCHRESPONSE .
Your service will look like this :
LAUNCHRESPONSE: launchResponseObject[] = [];
async getData() {
try {
this.LAUNCHRESPONSE = await this.http
.get<launchResponseObject>(
`${$apiUrl}`
)
.toPromise();
console.log(LAUNCHRESPONSE.response.url)
console.log(LAUNCHRESPONSE.response.token)
} catch (error) {
console.log(`Promise rejected with ${JSON.stringify(error)}`);
}
}
getStoredResponseData(){
return this.LAUNCHRESPONSE;
}
You can call the getStoredResponseData() declared inside the service to get the response details later on.