简体   繁体   English

Restangular使用save()

[英]Restangular use save()

I'm playing with Restangular and I want to make a call to .save() to update or create an entity. 我正在玩Restangular,我想调用.save()来更新或创建一个实体。 From Restangular github page I can see that it is possible to update or create a new account. 从Restangular github页面我可以看到可以更新或创建一个新帐户。 But if there are no accounts on the server I get method does not exists. 但是如果服务器上没有帐户,我得到的方法就不存在了。 (firstAccount is undefined) (firstAccount未定义)

Restangular.all('accounts').getList().then(function(accounts) {
  var firstAccount = accounts[0];
  firstAccount.title = "New title"
  // PUT /accounts/123. Save will do POST or PUT accordingly
  firstAccount.save();
});

My question is how do I make firstAccount a restangular object that will go to the correct url (POST /accounts) when I call firstAccount.save() if there are no accounts in the response? 我的问题是,如果响应中没有帐户,当我调用firstAccount.save()时,如何将firstAccount设置为一个restangular对象,该对象将转到正确的url(POST / accounts)?

If you are trying to create a new element, you may restangularize it: 如果您正在尝试创建新元素,可以将其重新组合:

var account = {
    title: 'New Title'
};
var restangularAccount = Restangular.restangularizeElement(null, account, 'accounts');
restangularAccount.save();

That will do an HTTP POST to /accounts 这将对/ accounts进行HTTP POST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM