AngularJS错误,“无法读取未知属性”

时间:2018-10-05 22:40:26

标签: angularjs angularjs-controller angularjs-factory

我试图创建一个工厂来检索我创建的简单网页的天气数据,但是,在尝试在工厂中调用该函数时,我陷入了困境。我不喜欢丹·华林(Dan Wahlin)关于Udemy的课程,但是我无法弄清楚为什么我得到了错误。好像我做错了什么,但我无法弄清楚。 这是代码

HTML

<!DOCTYPE html>

<div ng-controller="WeatherController" style="position:absolute; top:0px; ">
    {{weather.weather.main}}<br>
    <img src='http://openweathermap.org/img/w/10d.png' height="100px" width="100px">
</div>

<div style="background-color:white; position: absolute; bottom:0px;">
    <canvas id="canvas" width="400" height="400">
    </canvas>
</div>

<script src="script/angular.min.js"></script>
<script src="app/app.js"></script>
<script src="app/services/WeatherFactory.js"></script>
<script src="app/controllers/WeatherController.js"></script>
<script src="script/clock.js"></script>

app.js

(function () {
angular.module('displayApp', []);

}());

WeatherController.js

(function () {

var WeatherController = function ($scope, $log, $http, weatherFactory) {
    $scope.weather = "";

    function init() {            
        weatherFactory.getWeather() //******This line stops with error*****
            .then(function (response) {
                $scope.weather = response.data;
            }, function (data, status, headers, config) {
                $log.log(data.error + ' ' + status);
            });

        // $scope.weather = "Get the weather?"
    }

    init();

};

WeatherController.$inject = ['$scope', 'weatherFactory'];

angular.module('displayApp').controller('WeatherController', WeatherController);

}());

WeatherFactory.js

(function () {
var weatherFactory = function ($http) {

    var factory = {};

    factory.getWeather = function () {
        //return $http.get('api.openweathermap.org/data/2.5/weather?q=Rancho Santa Margarita&appid=60f84f7ee9256ef5057de8b616105ab9');
        return "Get the weather";
    };

    return factory;
};

weatherFactory.$inject = ["$http"];

angular.module('displayApp').factory('weatherFactory', weatherFactory);

}());

特定错误是 无法读取未定义的属性“ getWeather”     在初始化时(WeatherController.js:17)

我想念什么,或者我做错了什么?

任何帮助都将受到赞赏。 谢谢。

1 个答案:

答案 0 :(得分:1)

您缺少几次注射。您当前有:

WeatherController.$inject = ['$scope', 'weatherFactory'];

您的论据是$scope, $log, $http, weatherFactory。只需添加缺少的注射剂即可:

WeatherController.$inject = ['$scope', '$log', '$http', 'weatherFactory'];