2016-04-23 52 views
0

爲什麼console.log(響應)未包含來自服務器的響應。我如何獲得SpringMVC返回的「1」或「0」?

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


app.factory('baseRequest', ["$resource", function ($resource) { 

    return $resource("/apis/:id/:method/", {method: '@method', id: '@id'}, { 

     query: {method: 'get', isArray: false} 
    }); 

}]); 


app.controller("MyCtrl", ["$scope", "baseRequest", function ($scope, baseRequest) { 


    $scope.deleteUser = function (id) { 

     baseRequest.delete({method: "deleteUser.req", id: id}, function (response) { 

      //I can't get the response data from server side here. 

      console.log(response); 

     }, function (error) { 

      console.log(error); 

     }); 
    }; 

}]); 

這裏是我的文件用SpringMVC,它retruns信息「1」或「0」 ,但我並不怎麼弄呢?

@ResponseBody 
    @RequestMapping(value = "/{id}/deleteUser", method = RequestMethod.DELETE) 
    public String deleteUser(@PathVariable("id") Integer id) { 

     System.out.println(id); 


     if (userDao.deleteUser(id)) { 


      return "1"; 

     } else { 

      return "0"; 
     } 

    } 
+0

爲什麼你要在資源工廠中傳遞一個方法變量? –

回答

0

整個代碼對我來說似乎不對。其實你的工廠應該是這樣的:

app.factory('baseRequest', ["$resource", function ($resource) { 

return $resource("/apis/:id", { id: '@id'}, { 

    query: {method: 'get', isArray: false} 
}); 

}]); 

,你控制器應該是這樣的:

app.controller("MyCtrl", ["$scope", "baseRequest", function ($scope, baseRequest) { 


$scope.deleteUser = function (id) { 

    baseRequest.delete({id: id}, function (response) { 

     //I can't get the response data from server side here. 

     console.log(response); 

    }, function (error) { 

     console.log(error); 

    }); 
}; 

}]); 

當你定義一個資源到端點,angularjs自動創建的四種方法(動詞)(獲得,刪除,放置,張貼)給你。所以你不需要將方法名稱傳遞給web api。

+0

我是Angularjs的初學者。但根據你的建議,我對此有困惑。如何客戶端方法'刪除'請求到服務器端'方法'deleteUser',它有一個@RequestMapping like value =「/ {id}/deleteUser」。 – JSO