【问题标题】:Angular $resource not delivering the right dataAngular $resource 没有提供正确的数据
【发布时间】:2018-05-04 10:56:06
【问题描述】:

在我的控制器内部,我进行了以下 API 调用:

weatherApp.controller('forecastController', ['$scope', '$resource', 'cityService', function($scope, $resource, cityService){
    $scope.city = cityService.city;

    $scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {callback: 'JSON_CALLBACK'}, {get: {method: 'JSONP'}});
    $scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: 4, APPID: 'xxxxxx' });

    console.log($scope.weatherResult)
}]);

作为回报,我得到了一个承诺,但它没有返回正确的信息并且无法获取数据。

我认为问题在于我如何将 API 密钥插入到调用中。有人有什么想法吗?

【问题讨论】:

  • 启用了 api jsonp 吗?不是所有的
  • 您使用的是哪个版本的 AngularJS?当前的文档说不要使用JSON_CALLBACK
  • 我正在使用1.3.0-rc.2
  • 你必须这样做吗?我的意思是,即使使用稳定的 1.3 版本而不是发布候选版本也会更可取
  • 对于这个特定的项目,我很遗憾。 ://

标签: javascript angularjs jsonp


【解决方案1】:

所以我设法解决了这个问题,并得到了一个承诺,并用以下代码作为回报:

weatherApp.controller('forecastController', ['$scope', '$resource', 'cityService', function($scope, $resource, cityService){
    $scope.city = cityService.city;

    $scope.weatherAPI = $resource("http://api.openweathermap.org/data/2.5/weather/?APPID=d98c063da512b5ab03e39ac4a158b41f", {
    get: {method: "JSONP"}});

    $scope.weatherResult = $scope.weatherAPI.get({q: $scope.city, cnt: 5});


    console.log($scope)
    console.log($scope.weatherResult)
}]);

我删除了callback :'JSON_CALLBACK',因为它已被弃用并且会报错。我还从请求 URL 中删除了 daily,因为它不再提供,并将其替换为 forecast,如 API docs 中所示。现在,以前我将城市的参数设置为“纽约,纽约”,但出于某种奇怪的原因,openweathermap api 不需要状态(?如果我错了,有人纠正我)。所以我删除了这个州,把它留给了这座城市——>即“纽约”、“新奥尔良”、“伦敦”等。

这似乎是用正确的数据返回一个承诺。

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 2018-02-27
    • 2023-04-02
    • 2013-01-04
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多