0
我對Angular有點新東西,使用控制器,工廠爲$ http請求保留方法。
-------------- In Service ------------------------------
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);
}
什麼我的代碼有問題嗎?
HTTP是異步的。您不能期望您在發送請求後立即收到回覆。將console.log()行放入傳遞給then()的函數中。 –
@JBNizet是對的,在你的代碼合同中首先記錄下來,然後填入數據。如果您想調試它,請嘗試將console.log()放入承諾中,直接填寫合同對象後。 – Damiano
我認爲你需要刪除工廠函數中的then函數,你返回http.get,然後在控制器中執行(然後函數),就像你在做 –