Reputation: 15555
I've been returning requests from my functions like this:
makeConnection(data: any) {
console.log('makeConnection');
return this.api.get(data.url, data.dataToSend);
}
So I can subscribe like this: makeConnection.subscribe();
Now I need to check if a variable named urls
is set before making an API call So I thought of making a promised function like this
checkIfUrlsPresent():Promise<boolean> {
return new Promise((resolve, reject) => {
if(this.urls) {
resolve(true);
return;
}
this.api.get('/service', null).subscribe((response) => {
console.log(response);
this.urls = response.value.urls;
resolve(true);
});
});
}
And now my service functions look like this:
requestService(data) {
this.checkIfUrlsPresent().then(() => {
console.log('requestService');
let dataToSend = this.api.createFormData(data);
return this.api.post('/service/request/', dataToSend);
})
}
But now I won't be able to subscribe to my function like requestService(data).subscribe()
So my question is how to keep my present flow working while adding this promise or is there any way to check that my variable is set before making a call while keeping this flow working.
Note: The problem is that I'm making all my api calls from one files and there are too many functions that calls these APIs so I need this way so that I won't need to make changes in all my pages to check if url is present.
Upvotes: 1
Views: 845
Reputation: 370779
Have requestService
return the chained promises, and call .then
on it:
requestService(data) {
return this.checkIfUrlsPresent().then(() => {
console.log('requestService');
let dataToSend = this.api.createFormData(data);
return this.api.post('/service/request/', dataToSend);
})
}
// ..
instance.requestService(someData)
.then(service => service.subscribe())
Upvotes: 1
Reputation: 41417
Almost there. need to return the promise inside the function as well
requestService(data) {
return this.checkIfUrlsPresent().then(() => { // return the promise
console.log('requestService');
let dataToSend = this.api.createFormData(data);
return this.api.post('/service/request/', dataToSend);
})
}
Upvotes: 1