It seems like I'm attempting to force a square peg into a round hole as I work with Angular2 and Typescript. I've created a Javascript module that serves as an API client library for the API I'm utilizing. This library simplifies tasks such as setting up API keys, switching keys based on specific data criteria, etc. Essentially, it's just a utility library.
Most of the methods in this library follow a common pattern where you provide a query term and then execute a callback function.
For instance:
API.searchAutocomplete("angular", function(err, data) {
// handle the data/error
});
Within the searchAutocomplete method:
searchAutocomplete: function(query, callback) { // set up request with data payload, url, headers, etc
$.ajax(settings)
.done(function(response) {
// callback with success
})
.fail(function () {
// callback with error
});
}
I'm facing challenges trying to figure out how to implement this function in Typescript within an Angular service using Promises. It feels like trying to fit a square peg into a round hole. Should I just pass a callback within the service and treat it like traditional Javascript?
This is my attempt so far:
public getAutocomplete(query:string): Promise < any > {
return new Promise((resolve, reject) => {
API.searchAutocomplete(query, function (err, result) {
if (err) {
reject(err);
return;
}
resolve(result);
});
});
}
Additionally, although I have managed to integrate the library into my Angular app, I am unable to make any requests through it. Even when debugging in the console and accessing the library object directly, no network requests seem to be triggered. This behavior is quite perplexing to me.
Edit: I have resolved this issue now.
Upon configuring my service call to return a promise, I realized that I needed to subscribe to the promise to execute it correctly. I believe there is still room for improvement in terms of understanding how to structure my service call to return an observable and map the callback response.