Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue resource - dynamically determine http method

I would like to dynamically determine the appropriate http method and make a single api call. However an exception is thrown when I call the method.

I expect that I am doing something wrong rather than this being a vue-resource bug. Would anyone have any advice? Thanks

For example:

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}`)
})

A javascript TypeError is thrown with message "this is not a function"


The code below works, but a bit long winded.

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}`)
    })
}
like image 606
pymarco Avatar asked Jul 09 '26 18:07

pymarco


1 Answers

You need to bind the function to the current context.

let method = this.model.id ? this.$http.put.bind(this) : this.$http.post.bind(this)

Or just use the indexer approach.

let method = this.model.id ? 'put' : 'post'
this.$http[method](...).then(...)
like image 57
Bert Avatar answered Jul 11 '26 07:07

Bert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!