【问题标题】:http post call not working from angularjshttp post调用无法从angularjs工作
【发布时间】:2015-10-09 19:32:57
【问题描述】:

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

我的代码如下:

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 {       
   .....
}

【问题讨论】:

    标签: javascript json angularjs rest


    【解决方案1】:

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

    【讨论】:

    • 在工厂$scope根本没有使用
    • 正确,我在答案中添加了注释。
    • 谢谢。我已将代码更改为 app.factory('savenote', ['$http', function ($http) { return { save: function () { return $http({ method: 'POST',....
    【解决方案2】:

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

    所以更新你的控制器功能如下:

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

    $http 遗留的 promise 方法成功和错误已经 已弃用。请改用标准 then 方法。如果 $httpProvider.useLegacyPromiseExtensions 设置为 false 然后这些 方法会抛出 $http/legacy 错误。

    【讨论】:

    • 'views/addNote.html' 如下...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2014-02-10
    • 2017-04-22
    • 2017-07-03
    相关资源
    最近更新 更多