Javascript API、.factory、.controller错误

Javascript API、.factory、.controller错误,javascript,json,angularjs,api,rest,Javascript,Json,Angularjs,Api,Rest,我试图从数据库中获取数据。 这是JS代码: var app = angular.module('ForecastApp', []); console.log('in app'); //fetches weather data from service var res =""; app.factory('forecast', ['$http', function($http) { $http.get('https://s3.amazonaws.com/codecademy-content/

我试图从数据库中获取数据。 这是JS代码:

var app = angular.module('ForecastApp', []);
console.log('in app');

//fetches weather data from service
  var res ="";
app.factory('forecast', ['$http', function($http) {

$http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json')
          .success(function(data) { console.log(data); res = data; })
          .error(function(err) { console.log(err); res = err;});
          return res;
}]);

//Save weather data into $scope.fiveDay
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
      $scope.fiveDay = res;
      console.log('in controller');
    }]);
然后我在主HTML文件中运行:

<body ng-app="ForecastApp">
    <div class="main" ng-controller="MainController">
      ...
            <h1>{{ fiveDay.city_name }}</h1>
...

...
{{fiveDay.city_name}
...

fiveDay.city\u name
不返回任何内容,只显示空白
fiveDay
应该具有
res
的值,这是一个对象,对吗?我不明白为什么五天。城市名称不是纽约。

我提供了一个简单的解决方案,只是在控制器中使用$http服务

var-app=angular.module('ForecastApp',[]);
console.log('in-app');
//将天气数据保存到$scope.fiveDay中
app.controller('MainController',['$scope','$http',函数($scope,$http){
$http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json')
.success(函数(数据){console.log(数据);$scope.fiveDay=data;})
.error(函数(err){console.log(err);});
console.log('in controller');
}]);

...
{{fiveDay.city_name}

如果您仍然想使用自定义服务,这是一种方法

app.factory('forecastService', ['$http', function($http) {
  return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json');
}]);

app.controller('MainController', ['$scope', 'forecastService', function($scope, forecastService) {
  forecastService.then(function(success) { $scope.fiveDay = success.data});
}]);
您在这里的服务将返回一个承诺,您可以在该承诺中使用
。然后
方法。 这样控制器就不需要知道关于URL的任何事情

在使用angular时,您不希望脚本中出现任何全局变量。这正是angular services/工厂的原因。它们提供了一种在多个控制器和其他服务之间共享数据的方法


这是一个。

尝试创建主控制器的引用,然后显示城市名称。像
ng controller=“MainController as main”
然后
{{{main.fiveDay.city\u name}
它成功了,谢谢!现在显示的是“纽约”。你能告诉我什么地方做得不对吗?如果你看不到,我想你不熟悉异步处理和承诺。对您的问题的简短回答是:您的forecast服务在解析$http.get之前返回res。我建议您阅读更多关于javascript异步处理的内容,因为它对web编程非常重要。感谢您提供的解决方案和提示。