【问题标题】:Send by post with restangular用restangular邮寄
【发布时间】:2016-05-06 20:01:43
【问题描述】:

我正在尝试通过邮寄一个带有restangular的json,但这不会给我任何回报。

代码:

$scope.userPost = {

        title: 'foo',
        body: 'bar',
        userId: 1
    }

    $scope.registerUser=function(){
        $scope.people = Restangular.all('post').post($scope.userPost);
        console.log($scope.people);
    }

它返回给我这个:

{ "restangularCollection": false, "$object": {} }
http://jsonplaceholder.typicode.com/post 404 (Not Found)

通常我将它与 ajax 一起使用,它会返回一个 json:

$.ajax('http://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  data: {
    title: 'foo',
    body: 'bar',
    userId: 1
  }
}).then(function(data) {
  console.log(data);
});

有什么想法吗?

【问题讨论】:

  • http://jsonplaceholder.typicode.com/post !== http://jsonplaceholder.typicode.com/posts 也返回一个承诺,所以你需要使用Restangular.all('post').post($scope.userPost).then(function(data) { console.log(data); });得到响应

标签: angularjs json rest restangular


【解决方案1】:

Restangular 适用于 Promise,因此,您应该执行以下操作:

$scope.registerUser = function () {
    Restangular.all('post').post($scope.userPost).then((data) => {
        $scope.people = data;
        console.log($scope.people);
    });
}

或者您可以利用它的enhanced promises 并执行以下操作:

$scope.registerUser = function () {
    $scope.people = Restangular.all('post').post($scope.userPost).$object;
}

【讨论】:

    【解决方案2】:

    在 Angular 4+ 中

    constructor(private restangular: Restangular){}
    
    // latter in your method
    const baseUsers = this.restangular.all('post');
    baseUsers.post({'title':'foo','body': 'bar','userId': '1'})
    .subscribe(data => { console.log(data); });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多