1

내 프로젝트 (설정 번호, 프로젝트 이름, 기본 연락처 등)에 대한 구성 정보가 들어있는 json 파일에 대한 액세스 권한을 부여하려고합니다. 공장을 만들었습니다. http.get을 사용하여 json 파일을 검색하면 해당 데이터를 내 컨트롤러로 가져올 수 있지만 컨트롤러의 어느 위치에서든 액세스 할 수는 없습니다.출처 http.get에서 출고 된 데이터를 전체 컨트롤러에 액세스 AngularJS

나는 공장을 쓰지 않았기 때문에 그것을 다른 사람의 질문에 대한 대답으로 발견했다. 그리고 그것을 거의 완전히 복사 했으므로 내가하려는 것을 성취하려는 올바른 방법이 아니라면 나를 바로 잡아라. 여기

app.factory('configFactory', ["$http", function($http) { 

    var configFactory = { 
     async: function() { 
      // $http returns a promise, which has a then function, which also returns a promise 
      var promise = $http.get('assets/json/config.json').then(function(response) { 
       // The then function here is an opportunity to modify the response 
       console.log(response.data.config); 
       // The return value gets picked up by the then in the controller. 
       return response.data.config; 
      }); 
      // Return the promise to the controller 
      return promise; 
     } 
    }; 
    return configFactory; 

}]); 

내 컨트롤러 :

app.controller('footerController', ['$scope', '$rootScope', 'configFactory', function footerController($scope, $rootScope, configFactory) { 
    var body = angular.element(window.document.body); 
    $scope.onChange = function(state) { 
     body.toggleClass('light'); 
    }; 
    configFactory.async().then(function(d) { 
     $scope.data = d; 
     // this console log prints out the data that I am trying to access 
     console.log($scope.data); 
    }); 
    // this one prints out undefined 
    console.log($scope.data); 
}]); 

그래서 기본적으로 내가 아닌 외부에서 그의를 검색하는 데 사용되는 함수 내 데이터에 대한 액세스 권한이 여기

는 공장입니다. rootScope로이 문제를 해결할 수는 있지만 적절한 해결책은 아니라고 생각하기 때문에이를 피하려고합니다.

도움이 될만한 내용이지만 http.get과 약속 및 모든 내용에 대한 나의 첫 경험이므로 자세한 설명은 매우 감사하겠습니다.

[EDIT 1] 구성 파일의 변수를 웹 응용 프로그램에서 조작해야하므로 상수를 사용할 수 없습니다.

+0

요청이 완료되기 전에 먼저 'console.log'가 호출되므로'then '외부에서 데이터를 가져올 수 없습니다. . 이것이 비동기 코드의 작동 방식입니다. – estus

+0

@estus 그래서 문제를 해결하려면 어떻게해야합니까? 나는 (10ms와 같은) 짧은 지연을주기 위해 타임 아웃 기능을 추가 할 수 있지만 그것은 단지 해커처럼 보인다. –

+2

'then' 콜백 내에서'configFactory'에 관련된 모든 일을하기는 쉽습니다. – estus

답변

0

응답 데이터를 범위 변수에 할당하지 않고 공장에서 속성을 만들고 컨트롤러에서이 속성에 응답을 할당하면 약속이 해결됩니다.이 방법으로 다른 모든 컨트롤러에서 값을 가져옵니다. .

나는

app.factory('configFactory', ["$http", function($http) { 

    var configFactory = { 
     async: function() { 
      // $http returns a promise, which has a then function, which also returns a promise 
      var promise = $http.get('assets/json/config.json').then(function(response) { 
       // The then function here is an opportunity to modify the response 
       console.log(response.data.config); 
       // The return value gets picked up by the then in the controller. 
       return response.data.config; 
      }); 
      // Return the promise to the controller 
      return promise; 
     }, 
     config:'' // new proprety added 
    }; 
    return configFactory; 

}]); 

    app.controller('footerController', ['$scope', '$rootScope', 'configFactory', function footerController($scope, $rootScope, configFactory) { 
    var body = angular.element(window.document.body); 
    $scope.onChange = function(state) { 
     body.toggleClass('light'); 
    }; 
    configFactory.async().then(function(d) { 
     // $scope.data = d; 
     configFactory.config=d; 
     // this console log prints out the data that I am trying to access 
     console.log($scope.data); 
    }); 
    // this one prints out undefined 
    console.log($scope.data); 
}]); 
+0

내 코드를 변경 했는데도 실행되지만 여전히 동일한 문제가 있습니다. 마지막 줄의 console.log 호출은 'undefined'를 반환합니다.이 함수는 함수 외부의 데이터에 액세스하지 못하는 것 같습니다. –

+0

대부분 컨트롤러의 몸체에 직접 로직을 쓰지는 않습니다. 일부 기능에서만 로직이있을 가능성이 큽니다. 그래서 당신이 할당 한 것 이외의 다른 함수에서이 설정을 사용하고 싶다면 ... 당신이 현재 코드에서 얻지 못하는 이유는 console.log가 직접적으로 컨트롤러의 시체가 나오고 약속이 해결되기 전에 사형 당하고있다. 이 코드를 일부 함수에 넣고 ng-click 또는 something과 같은 일부 이벤트에서이 함수를 호출하면 데이터를 가져오고 정의되지 않습니다 –

0

당신이 각 상수를 사용으로 봤어 아래처럼 공장과 컨트롤러를 업데이트 한? http://ilikekillnerds.com/2014/11/constants-values-global-variables-in-angularjs-the-right-way/ 값을 할당 한 결과없이 모든 컨트롤러에서 액세스 할 수있는 전역 변수로 활용할 수 있습니다.

+0

이 작업은 가능하지만 변수에 대한 액세스 권한이 필요합니다. 나는 이것을 포함하도록 질문을 편집 할 것이다. –