I'm working with Angular. I have a service called UserService, that handles login, authentication and user data requests.
The get method needs to check if the user has a valid (not expired) token for authentication before making the get
request.
So, if it has, make the request, if not, request a token and then make the request.
This get method needs to hide its complex requests. It has to return only a Promise as it was making only one request.
So, an example of usage:
UserService
.get()
.then(data => { ... })
.catch(error => { ... })
Check if the token is expired. If it is, return a request to refresh the token, and there, make and return the get request. If it is not, just make and return the get request. As below:
function get() {
if (isTokenExpired(token))
return $http
.post(url + '/refreshtoken', 'token=' + refreshToken)
.then(response => {
token = response.data.token
return $http.get(url + '?token=' + token)
})
.catch(response => { ... })
else
return $http.get(url + '?token=' + token)
}
But it's returning a promise that I will have to handle like this:
UserService
.get()
.then(request => {
request // THAT IS NOT GOOD
.then(data => { ... })
.catch(error => { ... })
})
.catch(error => { ... })
Anything like the usage example!
How to make this get method on service, which handles authentication like that and hides everything from the controller that will use, letting it like in the usage example?
But it's returning a promise for a promise that I will have to handle like this:
UserService.get().then(request => { request.then(data => { … }) })
No.
Promises do chain, any "promise for a promise" will implicitly be flattened to a promise for the inner result. Your "wrong solution" code simply works as is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With