2016-11-20 2 views
1

서비스에서 반환 한 데이터를 $ scope 속성에 할당하려고합니다. 어떻게 든 제대로 작동하지 않습니다. 서비스 메소드는 $ http.get을 통해 데이터를 올바르게 가져 오지만 컨트롤러의 $ scope에는 할당되지 않습니다.

app.service('StoreService', ['$http', function ($http) { 

    this.getStoreNamesService = function() { 
     console.log('getStoreNames called'); 
     $http.get('http://localhost:8080/storys') 
      .success(function (response, status) { 
       console.log(response); 
       return response; 
      }) 
    }; 
}]); 

app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) { 

    $scope.storeNames = StoreService.getStoreNamesService(); 
}]); 

응답을 인쇄하면 올바른 데이터가 제공됩니다. 그러나 $ scope.storeNames를 인쇄 할 때 뷰에는 정의되지 않은 데이터도 없습니다.

app.js :

var app = angular.module('BlankApp', ['ngMaterial', 'ngRoute']) 
.config(function($mdThemingProvider) { 
    $mdThemingProvider.theme('default') 
     .primaryPalette('teal') 
     .accentPalette('red') 
     .warnPalette('red'); 
}); 

app.config(function ($routeProvider) { 
    $routeProvider 
     .when('/addItem', { 
      templateUrl: 'templates/addItemForm.html', 
      controller: 'ItemFormController' 
     }) 
     .when('/', { 
     templateUrl: 'templates/first.html' 
     }) 
     .when('/store', { 
      templateUrl: 'templates/itemsInStore.html', 
      controller: 'StoreController' 
     }) 
     .when('/item/:itemId', { 
      templateUrl: 'templates/itemView.html', 
      controller: 'ItemController' 
     }) 
     .otherwise({ 
      template: '<h1>otherwise template</h1>' 
     }) 
}); 

스크립트 태그의 순서 :

<!-- Angular Material requires Angular.js Libraries --> 
<script src="js/angular-1.5.8/angular.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.min.js"></script> 

<!-- Angular Material Library --> 
<script src="js/AngularMaterial/angular-material.js"></script> 

<!-- Your application bootstrap --> 


<script src="js/app.js"></script> 
<script src="js/service/itemService.js"></script> 
<script src="js/service/StoreService.js"></script> 
<script src="js/controller/testController.js"></script> 
<script src="js/controller/SideNavController.js"></script> 
<script src="js/controller/ItemFormController.js"></script> 

<script src="js/controller/sampleController.js"></script> 
<script src="js/controller/ItemController.js"></script> 
+1

AJAX 호출이 완료되지 않고 함수가 befote 반환하기 때문에이 일어나고있다. $ scope를 매개 변수로 사용하여 콜백을 보내거나 Promise를 사용하십시오 – bugwheels94

답변

1

이 작동합니다 : 약속이 해결 한 후에 만 ​​변수 storeNames을 할당 할 수 있습니다

app.service('StoreService', ['$http', function ($http) { 

this.getStoreNamesService = function() { 
    console.log('getStoreNames called'); 
    return $http.get('http://localhost:8080/storys').then(
     function success(response, status) { 
      console.log(response); 
      return response; 
     }) 
    }; 
}]); 

app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) { 
    StoreService.getStoreNamesService().then(function(result){ 
     $scope.storeNames = result; 
    }); 
}]); 

. 당신이하는 방식대로, 약속은 변수에 지정되었습니다.

.success() 또한 사용되지 않습니다. 대신 .then()을 사용하십시오. 사물의

0

당신이 약속을 반환하는 것이 더 낫다 각도 사용하여 $ HTTP 서비스가 약속을 반환하고 당신이 할 수있는 성공 콜백을 범위로 옮기십시오.

app.service('StoreService', ['$http', function ($http) { 
    this.getStoreNamesService = function() { 
     return $http.get('http://localhost:8080/storys'); 
    }; 
}]); 

app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) { 
    StoreService.getStoreNamesService().then(function (response, status) { 
     $scope.storeNames = response.data; 
    }); 
}]); 

또는 다음과 비슷한 지연 객체를 만들 수 있습니다.

app.service('StoreService', ['$http', '$q', function ($http, $q) { 
    this.getStoreNamesService = function() { 
     var deferred = $q.defer(); 
     $http.get('http://localhost:8080/storys').then(function(response, status){ 
      deferred.resolve(response.data); 
     }); 
     return deferred; 
    }; 
}]); 

app.controller('ItemFormController', ['$scope', '$http', '$mdDialog', 'itemService', 'StoreService', function ($scope, $http, $mdDialog, itemService, StoreService) { 
    StoreService.getStoreNamesService().then(function (data) { 
     $scope.storeNames = data; 
    }); 
}]); 

이 범위 객체는 컨트롤러 내에서 채워야 두 경우 모두 $q

를 참조하십시오 : 그것은 단지 데이터가 아니라 $의 HTTP 상태 코드 등을 반환 제외하고는 약속에 반환됩니다.

1

커플 당신은

  1. 당신은 서비스 방법 getStoreNames에서 $의 HTTP 메소드에 의해 약속 개체 반환을 반환해야 착각이었다.
  2. 수정하기 위해 $scope (컨텍스트)을 전달하면 안됩니다.
  3. promise 객체에서 값을 얻으려면 .then 함수를 사용해야합니다.

    app.service('StoreService', ['$http', function ($http) { 
        this.getStoreNamesService = function() { 
        //return promise here 
        return $http.get('http://localhost:8080/storys'); 
        }; 
    }]); 
    

컨트롤러

StoreService.getStoreNamesService($scope).then(function(response){ 
    $scope.storeNames = response.data; 
});