http post调用不能从angularjs工作

时间:2015-10-09 19:32:57

标签: javascript json angularjs rest

我是AngularJS的新手。我已经包含了控制器,服务和调用其他服务的代码。请告知为什么电话没有到达休息服务。

我的代码如下:

ko.bindingHandlers.myVisible = {
    init: function(element, valueAccessor) {
        var visible = ko.unwrap(valueAccessor());
      if (visible) {
        $(element).show();
        $(element).data('bindingsApplied', true);
      } else {
        $(element).hide();
        $(element).data('bindingsApplied', false);
        return { controlsDescendantBindings: true };
      }
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var visible = ko.unwrap(valueAccessor());
        if (visible) {
            if (!$(element).data('bindingsApplied')) {
                ko.applyBindingsToDescendants(bindingContext, element);
                $(element).data('bindingsApplied', true);
            }
            $(element).show();
        } else {
            $(element).hide();
        }
    }
}

angularjs控制器如下

app.config(function ($routeProvider) {
   $routeProvider       
    .when('/addNewNote', {
     controller: 'AddNewNoteController',
     templateUrl:'views/addNote.html'
     })

调用http post rest服务的角度服务

    app.controller('AddNewNoteController', ['$scope','savenote',        function($scope,savenote) {

    savenote.success(function(eData){
            $scope.msg = eData;   

这是休息服务

 app.factory('savenote',['$http',function($scope,$http){

    return $http({
        method: 'POST',
        url: <url is pasted here>,
        dataType: 'json',
        data: {
        "title" : "123dddd",
        "contents" : "123ddddtttttt"
    },
        headers: { 'Content-Type': 'application/json; charset=UTF-8' }
    })          

 }]);

2 个答案:

答案 0 :(得分:0)

您忘记了$scope的类型提示:

app.factory('savenote',['$scope', '$http', function($scope,$http){

此外,您的工厂应该使用方法返回一个对象:

app.factory('savenote', ['$scope', '$http', function ($scope, $http) {
    return {
        save: function () {
            return $http({
                method: 'POST',
                url: "<url is pasted here>",
                dataType: 'json',
                data: {
                    "title": "123dddd",
                    "contents": "123ddddtttttt"
                },
                headers: {'Content-Type': 'application/json; charset=UTF-8'}
            });
        }
    };
}]);

使用如下:

savenote.send().then(function(eData) {});

另外,正如@SarjanDesai在他的评论中所述,$scope未在您的工厂中使用,因此您应将其删除。

答案 1 :(得分:0)

savenote返回$http对象,该对象具有then函数,用于调用成功和失败回调。

所以用下面的方法更新你的控制器功能:

savenote.then(function successCallback(eData) {
    $scope.msg = eData;   
}
  

$ http遗留承诺方法成功与错误   弃用。请改用标准方法。如果   $ httpProvider.useLegacyPromiseExtensions设置为false然后这些   方法将抛出$ http / legacy错误。