Angular服务不会触发

angular service doesn't fire

本文关键字:服务 Angular      更新时间:2023-09-26

我做了非常简单的plunker来显示我的问题。问题是我有一个变量,我想用初始应用加载来填充这个变量,为此我做了angular services,但由于某种原因,angular services没有在控制器内部触发。我错在哪里?

app.controller('MainCtrl', function($scope, optService) {
  $scope.priority = [];
  var exeService = function() {
    console.log('function fired')
     // this is firing
      optService.myOptions(function (result) {
        console.log('service fired')
     // this is not firing
          angular.forEach(result, function(value) {
              $scope.priority.push({value: value.name, label: value.name});
          });
      });
   }
  exeService()
  console.log($scope.priority)
  // shows an empty array
});

服务
(function () {
angular.module("app").factory("optService", ["$http", "$rootScope", "$q", "$log",
    function ($http, $rootScope, $q, $log) {
        var clearApi = "test.json";

        function myOptions () {
            return $http.get(clearApi)
                .then(function (response) {
                  console.log(response.data)
                  // shows an array
                    return response.data;
                });
        } 
        return {
          myOptions: myOptions
        }
        }])
}());

你应该这样做服务声明:

 app.controller('MainCtrl', ['$scope', 'optService', function($scope, optService) {

和控制器

  optService.myOptions().then(function (result) {
    console.log('service fired')
      angular.forEach(result, function(value) {
          $scope.priority.push({value: value.name, label: value.name});
      });
  });