1

私の SchoolyearController では、パラメータ schoolyears は未定義です。

schoolyearService で自分の schoolyears オブジェクトを取得し、その結果を SchoolyearController に挿入するにはどうすればよいですか?

サービス

'use strict';
angular.module('schoolyear').service('schoolyearService', function ($http) {

    return {
        getSchoolyears: function () {            
            var path = 'scripts/model/schoolyears.json';
            $http.get(path).then(function (response) {
                return response.data.schoolyears;  // The schoolyears here are the 6 expected JS objects in an array, so far so good but how do I get those objects into the SchoolyearController as parameter ?
            });
        }
    };
});

UIルーター

resolve: {
    schoolyearService: ['schoolyearService',
        function (schoolyearService) {
            return schoolyearService.getSchoolyears();
        }]
},

コントローラ

'use strict';
angular.module('schoolyear').controller('SchoolyearController', function ($scope, schoolyears) {

    $scope.schoolyears = schoolyears; // I do not want to do a $http request here I just want to get passed the data here !!!
});

アップデート

解決されたプロパティの学年がまだ定義されていないのはなぜですか?

工場

'use strict';
angular.module('schoolyearModule').factory('schoolyearFactory', function ($http) {

    return {
        getSchoolyears: function () {
            var path = 'scripts/model/schoolyears.json';
            $http.get(path).then(function (response) {
                return response.data.schoolyears;  // The schoolyears here are the 6 expected JS objects in an array
            });
        }
    };
});

UIルーター

resolve: {
    schoolyears: function(schoolyearFactory) {
        var schoolyears = schoolyearFactory.getSchoolyears();
        return schoolyears;
    }

},

コントローラ

'use strict';
angular.module('schoolyearModule').controller('ProjectsController', function ($scope, schoolyears) {

    $scope.schoolyears = schoolyears; // I do not want to do a $http request here I just want to get passed the data here !!!
});
4

1 に答える 1

2

解決された値には名前が付けられますschoolyearService(したがって、同じ名前のサービスと衝突します):

resolve: {
    schoolyearService: ...

しかし、名前を使用して注入しようとしていますschoolyears:

angular.module('schoolyear').controller('SchoolyearController', 
    function ($scope, schoolyears) {

schoolyearsどこでも同じ名前 ( ) を使用します。

resolve: {
    schoolyears: ...

また、サービスを定義するには、servoce() メソッドではなく、factory() メソッドを使用する必要があります。このservice()メソッドは、実際のサービス インスタンスであるオブジェクトを返す関数ではなく、コンストラクタ関数を引数として取ります。

編集:

getSchoolyears()さらに、サービス メソッドからは何も返されません。そうundefined返されます。必要なものは次のとおりです。

    getSchoolyears: function () {
        var path = 'scripts/model/schoolyears.json';
        return $http.get(path).then(function (response) {
            return response.data.schoolyears;
        });
    }
于 2014-08-09T20:31:11.907 に答える