AngularJS 错误,"Cannot read property of unknown"

AngularJS Error, "Cannot read property of unknown"

我正在尝试创建一个工厂来检索我正在创建的一个简单网页的天气数据,但是,我在尝试调用工厂中的函数时卡住了。我在 Udemy 上休假了丹·瓦林 (Dan Wahlin) 的课程,但我就是想不通为什么会出现错误。看起来我确实做错了什么,但我无法弄清楚。 这是代码

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)

我错过了什么,或者我做错了什么?

感谢您提供的任何帮助。 谢谢。

您错过了几次注射。您目前拥有:

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

你的论据是$scope, $log, $http, weatherFactory。只需添加缺少的注入:

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