$ scope.object未定义$ http承诺

时间:2016-01-23 18:01:15

标签: angularjs

我是Angular的新手,使用控制器,工厂为$ http请求保留方法。

--------------在服务中------------------------------ < / p>

        factory.getContract = function(guid) {
            return $http
                .get(Configuration.apiurl + '/contracts/' + guid, { headers: {"accesstoken": 'XXXXXXXXXX'}})
                .then(function (response) {
                    return response;
                });
        };

---------------在控制器------------------

$scope.getContract = function (guid) {
            ContractService.getContract(guid).then(
                function (response) {
                    var data = response.data;
                    $scope.contract = {
                        contract_status: data.contract_status,
                        car: data.car,
                        properties: data.data
                    };
                },
                function (response) {
                    console.log('Error while loading the contract,', response);
                }
            );
        };



if ($state.includes('contracts.edit')) {
            $scope.getContract($stateParams.guid);
            // In this controller, i check if requesting route is the Edit then get contract data. When i do this it works and fill the form with correct information. BUT AS I TRY TO ACCESS $scope.contract in console it says undefined
            console.log($scope.contract);
}

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

$ http.get正在返回Promise,所以如果要在控制器内部执行回调,只需从工厂中删除.then部分:

factory.getContract = function(guid) {
        return $http.get(Configuration.apiurl + '/contracts/' + guid, 
               { headers: 
                    {"accesstoken": 'XXXXXXXXXX'}
                });
}