HTTP post调用在angularjs中不起作用

http post call not working from angularjs

本文关键字:不起作用 angularjs post 调用 HTTP      更新时间:2023-09-26

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

我的代码如下:
app.config(function ($routeProvider) {
   $routeProvider       
    .when('/addNewNote', {
     controller: 'AddNewNoteController',
     templateUrl:'views/addNote.html'
     })

angularjs控制器如下

    app.controller('AddNewNoteController', ['$scope','savenote',        function($scope,savenote) {
    savenote.success(function(eData){
            $scope.msg = eData;   

调用http post rest服务的angular服务

 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' }
    })          
 }]);

这是剩下的服务

@Path("/savenote")
@POST
@Consumes(MediaType.APPLICATION_JSON)  
@Produces(MediaType.APPLICATION_JSON)  
  public UserMessages saveNewNote(Note note) throws IOException {       
   .....
}

您忘记了$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没有在你的工厂使用,所以你应该删除它。

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

用下面的语句更新你的控制器函数:

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

$http遗留的承诺方法的成功和错误已经弃用。请使用标准的then方法。如果httpProvider美元。useLegacyPromiseExtensions设置为false方法将抛出$http/legacy错误。