When utilizing vue.js along with the axios library to make requests to my API, I aim to configure it globally and display a loading message when the request takes too long.
I discovered that by using axios interceptors, I can set up axios configuration on a global scale.
axios.interceptors.request.use((config) => {
// Perform actions before sending the request
return config;
}, (error) => {
// Handle request errors
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use((response) => {
// Handle response data
return response;
}, (error) => {
// Handle response errors
return Promise.reject(error);
});
To display notifications, I rely on f3oall/awesome-notifications plugin (specifically the version for vue.js). Here's an attempt to incorporate it:
axios.interceptors.request.use((config) => {
this.$awn.info("Attempting to send request");
return config;
}, (error) => axios_error(error));
axios.interceptors.response.use((response) => {
this.$awn.success("Success!");
return response.data;
}, (error) => axios_error(error));
function axios_error(error) {
//this.$awn.alert("Request error"); // This line throws an error - Uncaught (in promise) TypeError: Cannot read property '$awn' of undefined
return Promise.reject(error);
}
However, I encounter some issues:
Firstly, I prefer not to use the success
method to display success messages. Instead, I want to utilize the asyncBlock()
method which displays a loader and blocks the screen until the promise is fulfilled, then triggers a callback or shows a new toast.
asyncBlock(promise, onResolve, onReject, html)
How can I implement this within the interceptors.request
and interceptors.response
functions?
Secondly, In the axios_error()
function, I cannot access this
. Thus,
this.$awn.alert("Request error");
does not work. Is there a way to resolve this issue?
All I want is to globally configure the following behavior: if a request exceeds 500ms in duration, display asyncBlock dots (a full-window loading message). If an error occurs during the request, show an error message - this.$awn.alert("Request error")
. If no errors arise, do not display any messages.
Is there a way to achieve this? Are there any alternative approaches?