Angularjs;在服务中使用 $http 返回引用而不是实际数据 [英] Angularjs; use $http in service returns reference instead of actual data

查看:16
本文介绍了Angularjs;在服务中使用 $http 返回引用而不是实际数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angularjs 中使用 services 指令非工厂,我需要将 json 文件填充到本地变量;

I'm using the services directive in Angularjs not factory and I need to populate a json file to local variable;

/* Contains projects on the town */
leMaireServicess.service('cityService', function($http) {

    // JSON regions and cities loader
    this.cities = [];

    // initCities 
    this.initCities = function() {
        this.cities = $http.get('data/census/cities.js').success(function(data) {
            return data;
        });
        return this.cities;
    };

    // Get city info
    this.getCity = function() {
        return this.cities;
    };
});

在我的控制器中我有

// Saved game controller
leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) {

    /* Control the town project slides */
    cityService.initCities();
    $scope.city = cityService.getCity();

    console.log($scope.city);
});

但是它返回的不是实际数据,而是返回;

But instead of returning the actual data, it returns;

Object {then: function, catch: function, finally: function, success: function, error: function}

推荐答案

您可以使用手表来完成这项工作(参见plunker)

You can use a watch to make this work (see plunker)

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,cityService) {
  //$scope.cities = [];
  $scope.service = cityService;
  cityService.initCities();


  $scope.$watch('service.getCity()', function(newVal) {
    $scope.cities = newVal;
    console.log(newVal)
  });


});

app.service('cityService', function($http) {
  var that = this;
  this.cities = [];

  this.initCities = function() {
      $http.get('data.js').success(function(data) {
          that.cities = data.cities;
      });
  };

  this.getCity = function() {
      return this.cities;
  };
});

这篇关于Angularjs;在服务中使用 $http 返回引用而不是实际数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆