2017-09-13 36 views
0

我正在使用Vue资源连接到我的后端api。我有一个表单组件,用于创建新资源项目和修改现有资源项目。表单工作正常,但是当我想保存表单时,它需要使用正确的http方法进行api调用。如果我正在创建一个新项目,它应该使用POST方法,如果我正在更新现有项目,它应该使用PUT方法。现在,我的形式保存方法看起来是这样的:Vue资源,使用相同的表单进行插入和更新

if(this.itemId > 0) { // Update existing item 
    myresource.update({id: this.itemId}, this.item).then(response => { 
     //... 
    }, response => { 
     //... 
    }); 
} 
else {  // Post new item 
    myresource.save({}, this.item).then(response => { 
     //... 
    }, response => { 
     //... 
    }); 
} 

基本上,我必须使用if语句来检查是否使用updatesave资源的功能,那么成功/失败的承诺都使用相同的码。有没有一些方法,以这两种方法具有这样的结合上面:

var method = this.itemId ? 'PUT' : 'POST'; 
myresource.request(method, {id: this.itemId}, this.item).then(response => { 
     //... 
    }, response => { 
     //... 
    }); 

上面的代码显然是行不通的,但有一个类似的方式来做到这一点不使用if声明和重复我的成功/每个请求类型失败的承诺?

回答

0

一个简单的办法是在一个单链创建基于条件的请求,然后连接其余的承诺:

const request = (this.itemId > 0) ? myresource.update ? myresource.save; 
request({ 
    id: this.itemId // Make the save call ignore the id 
}, this.item).then(response => { 
    // Shared code 
}); 
+0

这看起来像它应该很好地完成。谢谢! – matt