RESTful API调用没有更新本地数组

RESTful API call not updating local array?

本文关键字:数组 更新 API 调用 RESTful      更新时间:2023-09-26

我有一个从后台获取数据的工厂服务,我试图填充一个本地数组,如下所示:

(function() {
app.controller('UpdateProvidersCtrl', ['$scope', 'ngDialog', '$http', 'Provider', '$resource', '$window','SpecialtyService', function($scope, ngDialog, $http, Provider, $resource, $window,SpecialtyService) {
var specialties = [];
SpecialtyService.getService().then(function(data){
   $scope.specialty = data;
    angular.forEach(data.specialty, function(item){
       specialties.push(item);
    );
 });
    console.log(specialties);

console.log返回一个空数组,我知道数据正在被检索,因为我已经放置了其他console.log消息,并且承诺返回一个数组。

这是我的服务

app.factory('SpecialtyService', ['$resource', function($resource) {
  function SpecialtyService() {
    this.service = $resource('/api/specialty_search'); 
  };
  SpecialtyService.prototype.getService = function() {
    return this.service.get().$promise;
  };
  return new SpecialtyService;
}]);

是否因为异步调用而返回空?还是我做了什么根本性的错误?

试试这个:

function() {
app.controller('UpdateProvidersCtrl', ['$scope', 'ngDialog', '$http', 'Provider', '$resource', '$window','SpecialtyService', function($scope, ngDialog, $http, Provider, $resource, $window,SpecialtyService) {
var specialties = [];
SpecialtyService.getService().then(function(data){
   $scope.specialty = data;
    angular.forEach(data.specialty, function(item){
       specialties.push(item);
    );
   console.log(specialties);
 });

由于您的服务调用是异步的,您需要在正确的位置添加console.log(回调)