gpt4 book ai didi

Angularjs;在服务中使用 $http 返回引用而不是实际数据

转载 作者:行者123 更新时间:2023-12-02 11:28:23 24 4
gpt4 key购买 nike

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

/* 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;
};
});

在我的 Controller 中我有

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

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

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

但它没有返回实际数据,而是返回;

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

最佳答案

您可以使用 watch 来完成这项工作 ( 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 返回引用而不是实际数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com