简体   繁体   English

在使用$ http.get()获取部分数据之后,使用angularjs将数据发布到REST API

[英]posting data to REST API with angularjs after getting a part of the data using $http.get()

I have a backend written in django and it looks like this: 我有一个用django编写的后端,它看起来像这样:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "message_body": "Hi mam, you are amazing!!!",
        "deleted": false,
        "id": 7,
        "timestamp": "2017-08-23T15:22:00.676099Z",
        "moderator_approval_count": 0,
        "verified_by_moderators": true,
        "last_like_activity_id": 8,
        "last_like_count": 2,
        "likes": [
            {
                "message_id": 7,
                "liked": true,
                "unliked": false,
                "id": 7,
                "timestamp": "2017-08-26T05:56:02.167164Z",
                "user_id": 1
            },
            {
                "message_id": 7,
                "liked": false,
                "unliked": true,
                "id": 8,
                "timestamp": "2017-08-26T05:57:49.756284Z",
                "user_id": 1
            }
        ],
        "teacher_id": 5
    },
    {
        "message_body": "Hi sir, you are amazing ^ 34 !!!",
        "deleted": false,
        "id": 13,
        "timestamp": "2017-08-23T19:20:07.468438Z",
        "moderator_approval_count": 0,
        "verified_by_moderators": true,
        "last_like_activity_id": 6,
        "last_like_count": 1,
        "likes": [
            {
                "message_id": 13,
                "liked": true,
                "unliked": false,
                "id": 6,
                "timestamp": "2017-08-23T19:32:20.652049Z",
                "user_id": 1
            }
        ],
        "teacher_id": 6
    },
    {
        "message_body": "Hi sir, you are great!!!",
        "deleted": false,
        "id": 14,
        "timestamp": "2017-08-25T08:49:34.158602Z",
        "moderator_approval_count": 0,
        "verified_by_moderators": true,
        "last_like_activity_id": -1,
        "last_like_count": 0,
        "likes": [],
        "teacher_id": 7
    },
    {
        "message_body": "You're a wonderful teacher, mam!",
        "deleted": false,
        "id": 15,
        "timestamp": "2017-08-26T15:14:44.745096Z",
        "moderator_approval_count": 0,
        "verified_by_moderators": true,
        "last_like_activity_id": -1,
        "last_like_count": 0,
        "likes": [],
        "teacher_id": 5
    }
]

I'm deploying it using a virtual environment. 我正在使用虚拟环境进行部署。 My html looks like this: 我的html看起来像这样:

<div class="form-group" ng-controller="createMessage">
        <label class="control-label" for="selectTeacher">To</label>
        <select class="form-control" id="selecT" ng-model="chosen.teacher" ng-options="teacher.name for teacher in teachers track by teacher.id" required>
        </select>
        <textarea class="form-control" id="message" cols="auto" rows="10" ng-model="note" placeholder="Write your message" required></textarea>
      </div>  
      <div>
        <button type="submit" class="form-control" id="subBtn" ng-click="postData(note, chosen.teacher.id)">Post</button>
      </div>

I've to use the chosen.teacher.id and note to post the message in the backend above. 我必须使用selected.teacher.id并注意将消息发布到上面的后端中。 Here's my app.js for the following: 这是我的以下app.js:

var app = angular.module('info', []);

app.controller('createMessage', function($scope, $http) {
    $scope.teachers = [];
    $scope.chosen = {};
    $http.get('http://127.0.0.1:10000/compliments/teachers/').
        then(function(response) {
            $scope.teachers = response.data;
        });
    $scope.chosen.teacher = { id : 5, name : 'Dr. Ananya Kanjilal'};
    var config = {
        headers: {
            'Content-type': 'application/json'
        } 
    };
});

function postData(message, t_id)    {
    $http.post('http://127.0.0.1:10000/compliments/messages/',
        {
            message_body: message,
            deleted: false,
            id: t_id
        },
        {
            headers: {
                'Content-type': 'application/json'
            }
        }).success(function(response)   {
            console.log("ok");
        }).error(function(response) {
            console.log("error");
            console.log(response.data);
        });
}

I'm getting no error but the data isn't being posted to the server. 我没有收到任何错误,但没有将数据发布到服务器。 I'm a newbie in front end. 我是前端的新手。 Please help with examples. 请提供示例。 Thanks in advance! 提前致谢!

ok, here's my solution: 好的,这是我的解决方案:

var app = angular.module('info', [])

app.controller('createMessage', function($scope, $http) {
    $scope.teachers = [];
    $scope.chosen = {};
    $http.get('http://127.0.0.1:10000/compliments/teachers/').
        then(function(response) {
            $scope.teachers = response.data;
        });
    $scope.chosen.teacher = { id : 5, name : 'Dr. Ananya Kanjilal'};
    $scope.postData = function()    {
    $http({
            url: 'http://127.0.0.1:10000/compliments/messages/',
            method: 'POST',
            data:   JSON.stringify({
                "message_body": $scope.note,
                "deleted": false,
                "teacher_id": $scope.chosen.teacher.id
            }),
            config:  {
                headers:
                    {
                        'Content-type': 'application/json'
                }
            }
        }).success(function(response)   {
            console.log("ok");
        }).error(function(response) {
            console.log("error");
            console.log(response.data);
        });
    }
});

i omitted the JSON.stringify() earlier and was the sole reason for TypeError 我之前省略了JSON.stringify(),这是TypeError的唯一原因

I am updating my answer as per your updated question 我正在根据您更新的问题更新答案

First of all in app.js define your postData function inside your controller and in a $scope object 首先在app.js ,在控制器内部和$ scope对象中定义postData函数

app.js app.js

var app = angular.module('info', []);

app.controller('createMessage', function($scope, $http) {
$scope.teachers = [];
$scope.chosen = {};
$http.get('http://127.0.0.1:10000/compliments/teachers/').
    then(function(response) {
        $scope.teachers = response.data;
    });
$scope.chosen.teacher = { id : 5, name : 'Dr. Ananya Kanjilal'};
var config = {
    headers: {
        'Content-type': 'application/json'
    } 
};
$scope.postData = function(message, t_id)    {
$http.post('http://127.0.0.1:10000/compliments/messages/',
    {
        message_body: message,
        deleted: false,
        id: t_id
    },
    {
        headers: {
            'Content-type': 'application/json'
        }
    }).success(function(response)   {
        console.log("ok");
    }).error(function(response) {
        console.log("error");
        console.log(response.data);
    });
}
});

And in your html file, the last div containing ng-click function is outside your ng-controller div. 并且在您的html文件中,包含ng-click函数的最后一个div在ng-controller div之外。 The correct way would be 正确的方法是

<div class="form-group" ng-controller="createMessage">
    <label class="control-label" for="selectTeacher">To</label>
    <select class="form-control" id="selecT" ng-model="chosen.teacher" ng-options="teacher.name for teacher in teachers track by teacher.id" required>
    </select>
    <textarea class="form-control" id="message" cols="auto" rows="10" ng-model="note" placeholder="Write your message" required></textarea>
  <div>
    <button type="submit" class="form-control" id="subBtn" ng-click="postData(note, chosen.teacher.id)">Post</button>
  </div>
  </div> 

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

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