I am trying to dynamically determine the appropriate HTTP method and make a single API call. However, I keep running into an exception when I attempt to call the method.
Instead of assuming it's a bug with vue-resource
, I believe I may be making a mistake in my code. Does anyone have any advice on how to resolve this issue? Thanks in advance.
Here is an example of what I'm attempting to do:
let method = this.$http.post
if (this.model.id) {
method = this.$http.put
}
method(
this.url,
this.model,
options
).then(response => {
this.$router.push(this.redirect_to)
}).catch(response => {
console.log(`Error: ${response.statusText}`)
})
When I try to execute the above piece of code, I encounter a javascript TypeError
which says "this is not a function".
The following code below does work, but it feels a bit cumbersome to handle both situations separately:
if (this.model.id) {
this.$http.put(
this.url,
this.model,
options
).then(response => {
this.$router.push(this.redirect_to)
}).catch(response => {
console.log(`Error: ${response.statusText}`)
})
} else {
this.$http.post(
this.url,
this.model,
options
).then(response => {
this.$router.push(this.redirect_to)
}).catch(response => {
console.log(`Error: ${response.statusText}`)
})
}