获取服务后的回复

时间:2014-08-22 08:42:00

标签: angularjs angularjs-service

我正在尝试通过service发布我的表单数据,但如果我想在控制台中获取响应,我发现undefined你能告诉我我犯了什么错误, 我是棱角分明的新人,所以很难发现问题。这是我的代码

commonApp.service('CommonServices',function($http){

        this.saveData=function(DataToInsert){
        $http({
            method  :"POST",
            data    :DataToInsert,
            url     : 'myurl',
            //headers :{'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(programApiResponse){

            console.log(programApiResponse);
            return programApiResponse;


        }).error(function(programApiResponse){

            return programApiResponse;

        });

        };
    });

和我的控制器

$scope.makeprogram=function(){
        //console.log($scope.programdata);

        $scope.ProgInsResponse=CommonServices.saveData($scope.programdata);

        console.log('1'+$scope.ProgInsResponse);
    }

2 个答案:

答案 0 :(得分:0)

你没有在

返回承诺
this.saveData = function(DataToInsert){
    $http({
    ...

这应该是

this.saveData=function(DataToInsert){
    return $http({
    ...

然后,如果你可以添加自己的处理程序

CommonServices.saveData($scope.programdata)
    .then(...)

最后但并非最不重要的是,如果你有一个不错的浏览器,你可以只记录对象,不要记录字符串。

CommonServices.saveData($scope.programdata)
    .then(function(){
        console.log(arguments);
    });

答案 1 :(得分:0)

这是异步性问题。试试这个

$scope.makeprogram=function(){

        CommonServices.saveData($scope.programdata).then(function() {
           console.log('1'+$scope.ProgInsResponse);
       }); 
    }

由于你要回复承诺,你需要在回应之前等待。

相关问题