gpt4 book ai didi

javascript - Angular Controller 不控制台记录数据。然而,Service 正在传递数据。

转载 作者:行者123 更新时间:2023-11-28 00:02:28 24 4
gpt4 key购买 nike

我的后端已链接到该服务。当我在 Controller 上调用函数时,它会在服务中执行该函数,并控制台记录数据。从服务到 Controller 的数据是通过 Promise 传递的。我正在获取适当的数据。但是,为了将数据绑定(bind)到我的示波器上,我需要 Controller 上的数据。当我通过控制台记录数据时,控制台日志未定义。我不确定我做错了什么。

Controller

"use strict";

app.controller("weatherCtrl", function($scope, weatherService) { //START APP

// ***********************************************
// *************** GET LATEST DATA ***************
// ***********************************************
$scope.getTodaysWeather = function() { //OPEN FUNCTION
weatherService.getWeatherData().then(function(data) {
console.log("Weather Control", data);
// $scope.todaysWeather = data;

});
}; //CLOSE FUNCTION

$scope.getTodaysWeather(); //INVOKE THE FUNCTION

}); //CLOSE APP

服务

"use strict";

app.service("weatherService", function($http, $q) { //START APP

// ***********************************************
// *************** GET LATEST DATA ***************
// ***********************************************
this.getWeatherData = function() { //OPEN FUNCTION
var defer = $q.defer(); //promise
$http.get("/app/weather/weatherData")
.success(function(response) { //callback for resolve
console.log("Main Service Data", response);

var weatherDataObj = response.report;
var weatherDataArray = [];

for (var key in weatherDataObj) {
weatherDataArray.push({
max_temp: weatherDataObj.max_temp,
min_temp: weatherDataObj.min_temp
});
}
console.log("weatherDataArray from Service", weatherDataArray);
defer.resolve(); //successful promise
})
.error(function(err) {
defer.reject(err);
});
return defer.promise; //return promise "q"
}; //CLOSE FUNCTION

}); //CLOSE APP

最佳答案

"use strict";

app.service("weatherService", function($http, $q) { //START APP

// ***********************************************
// *************** GET LATEST DATA ***************
// ***********************************************
this.getWeatherData = function() { //OPEN FUNCTION
var defer = $q.defer(); //promise
$http.get("/app/weather/weatherData")
.success(function(response) { //callback for resolve
console.log("Main Service Data", response);

var weatherDataObj = response.report;
var weatherDataArray = [];

for (var key in weatherDataObj) {
weatherDataArray.push({
max_temp: weatherDataObj.max_temp,
min_temp: weatherDataObj.min_temp
});
}
console.log("weatherDataArray from Service", weatherDataArray);
defer.resolve(weatherDataArray); //YOU NEED TO RESOLVE THE DATA
})
.error(function(err) {
defer.reject(err);
});
return defer.promise; //return promise "q"
}; //CLOSE FUNCTION

}); //CLOSE APP

关于javascript - Angular Controller 不控制台记录数据。然而,Service 正在传递数据。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31659427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com