AngularJS初始化提供者数据

时间:2016-03-15 16:34:16

标签: javascript angularjs

我有代码:

linkedList *createFreqTable(char *file) {
    int i = 0;
    int k = 0;
    int fCount = 0;
    int sizeLimit = 128;
    struct tnode *nodes = malloc(128 * sizeof(struct tnode));
    int character;

    FILE *stream = fopen(file, "r");
    if (stream == NULL) {
        /* handle this error */
        ...
        return NULL;
    }
    /* Scan the file until EOF */
    while ((character = fgetc(stream)) != EOF) {
        ...

我想在.run()方法中初始化数据(我不能使用.config()方法,因为它不允许传递任何像$ http这样的服务)。我找到了.run()方法,但是这段代码不起作用......数据没有保存在提供程序中。官方文件说:

“在创建注射器后执行此功能。对应用程序初始化很有用。”

我认为这是初始化数据的最佳方式。

3 个答案:

答案 0 :(得分:1)

您可能希望使用Angular Factory / Service来满足此类需求。这就是我做的。并将其传递给应用程序。该服务将成为您关于数据的单身或事实来源。



angular.module('myData.services', [])
  .factory('myData', ['$rootScope', '$http' , function($rootScope,$http) {

            var factory = {
                myData : {}
            };
    
            $http('/api/call', function(apiData) {
              factory.myData = apiData;
            });

            return factory;
        }]);




然后您可以在控制器中使用它:

angular.module('myApp.controllers', [])
    .controller('myCtrl', ['myData', '$scope', function(myData, $scope){
        $scope.users = myData;
    }]);

查看有关服务的文档:https://docs.angularjs.org/guide/services

答案 1 :(得分:0)

提供商配置只能在config块内执行,您无法在run块内执行此操作

虽然在配置应用时我没有找到加载users对象的理由。我说你应该使用service/factory来获取此信息。

<强>代码

angular.module('admin', [])
.service('users', function($http, $q) {
  var users = [];
  //make an get call to fetch users
  function getUsers() {
    return $http.get('database.php')
      .then(function(response) {
      data = response.data;
    });
  }

  //will make a call if users aren't there
  this.getData = function() {
    // Handled below two conditions
    // 1. If users aren't fetched the do an Ajax
    // 2. If last ajax doesn't return a data then DO it again..
    if (users.length > 0)
      return $q.resolve(data); //do return data using dummy promise
    return getUsers();
  };
  return users;
})

.controller('test', function($scope, users) {
   users.getData().then(function(data){
      console.log(data);
   });
});

答案 2 :(得分:0)

第二次尝试

angular.module('admin', [])
.factory('users', function ($http) {
  var users = {};
  var data = [];

  $http.get('database.php')
    .then(function (response) {
        data = response.data;
    });

  users.getData = function () {
  return data;
  };

  return users;
})
.controller('test', function ($scope, users) {
  console.log(users.getData());
});

我想私有数据。返回空数组,响应所有数据。