简体   繁体   English

如何在angularjs中的Restful API中传递数据

[英]How to pass data in restful api in angularjs

I want to add a new entry in a mysql table. 我想在mysql表中添加一个新条目。 I tested API from an advanced restful client. 我从一个高级的Restful客户端测试了API。 It's working fine. 一切正常。

but when I tried with angular js, entry is not getting added. 但是当我尝试使用angular js时,没有添加条目。

service code: 服务代码:

sampleApp.factory('Brand', function ($resource) {
   return $resource('http://<mydomain>/api/v1/brands/:id');
});

controller code: 控制器代码:

$scope.brand = new Brand();
$scope.brand.id = parseInt($scope.Brands[$scope.Brands.length-1].id, 10) + 1;
$scope.brand.name = $filter('toTitleCase')($scope.NewBrand.name);  
$scope.brand.image = '/images/brands/' + $filter('toLowerCase')($scope.NewBrand.name) + '.png'; 


Brand.save($scope.brand, function() {
        alert('data saved');    
        //data saved. do something here.
});

what is wrong here? 这是怎么了 can anyone help on this? 有人可以帮忙吗?

To convert to sending as form encoded instead of default application/json the following example is copied from the angular docs for $httpParamSerializerJQLike 为了转换为以编码形式发送,而不是默认的application/json格式,下面的示例从$ docsParamSerializerJQLike的角度文档中复制而来

.controller(function($http, $httpParamSerializerJQLike) {
  //...

  $http({
    url: myUrl,
    method: 'POST',
    data: $httpParamSerializerJQLike(myData),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });

});

You can also set global defaults for all $http in config phase of app 您还可以在应用程序的配置阶段为所有$http设置全局默认值

Also look up in $http docs alternative approach to pass serializer as a string name 还可以在$http docs中查找将序列化程序作为字符串名称传递的替代方法

If you are using jQuery the serializer is the same as $.param() 如果您使用的是jQuery,则序列化程序与$.param()相同

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

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